//Modal
(function(d){var k=d.browser.msie&&parseInt(d.browser.version)===6&&typeof window.XMLHttpRequest!=="object",m=d.browser.msie&&parseInt(d.browser.version)===7,l=null,f=[];d.modal=function(a,b){return d.modal.impl.init(a,b)};d.modal.close=function(){d.modal.impl.close()};d.modal.focus=function(a){d.modal.impl.focus(a)};d.modal.setContainerDimensions=function(){d.modal.impl.setContainerDimensions()};d.modal.setPosition=function(){d.modal.impl.setPosition()};d.modal.update=function(a,b){d.modal.impl.update(a,
b)};d.fn.modal=function(a){return d.modal.impl.init(this,a)};d.modal.defaults={appendTo:"body",focus:true,opacity:50,overlayId:"simplemodal-overlay",overlayCss:{},containerId:"simplemodal-container",containerCss:{},dataId:"simplemodal-data",dataCss:{},minHeight:null,minWidth:null,maxHeight:null,maxWidth:null,autoResize:false,autoPosition:true,zIndex:1E3,close:true,closeHTML:'<a class="modalCloseImg" title="Close"></a>',closeClass:"simplemodal-close",escClose:true,overlayClose:false,position:null,
persist:false,modal:true,onOpen:null,onShow:null,onClose:null};d.modal.impl={d:{},init:function(a,b){var c=this;if(c.d.data)return false;l=d.browser.msie&&!d.boxModel;c.o=d.extend({},d.modal.defaults,b);c.zIndex=c.o.zIndex;c.occb=false;if(typeof a==="object"){a=a instanceof jQuery?a:d(a);c.d.placeholder=false;if(a.parent().parent().size()>0){a.before(d("<span></span>").attr("id","simplemodal-placeholder").css({display:"none"}));c.d.placeholder=true;c.display=a.css("display");if(!c.o.persist)c.d.orig=
a.clone(true)}}else if(typeof a==="string"||typeof a==="number")a=d("<div></div>").html(a);else{alert("SimpleModal Error: Unsupported data type: "+typeof a);return c}c.create(a);c.open();d.isFunction(c.o.onShow)&&c.o.onShow.apply(c,[c.d]);return c},create:function(a){var b=this;f=b.getDimensions();if(b.o.modal&&k)b.d.iframe=d('<iframe src="javascript:false;"></iframe>').css(d.extend(b.o.iframeCss,{display:"none",opacity:0,position:"fixed",height:f[0],width:f[1],zIndex:b.o.zIndex,top:0,left:0})).appendTo(b.o.appendTo);
b.d.overlay=d("<div></div>").attr("id",b.o.overlayId).addClass("simplemodal-overlay").css(d.extend(b.o.overlayCss,{display:"none",opacity:b.o.opacity/100,height:b.o.modal?f[0]:0,width:b.o.modal?f[1]:0,position:"fixed",left:0,top:0,zIndex:b.o.zIndex+1})).appendTo(b.o.appendTo);b.d.container=d("<div></div>").attr("id",b.o.containerId).addClass("simplemodal-container").css(d.extend(b.o.containerCss,{display:"none",position:"fixed",zIndex:b.o.zIndex+2})).append(b.o.close&&b.o.closeHTML?d(b.o.closeHTML).addClass(b.o.closeClass):
"").appendTo(b.o.appendTo);b.d.wrap=d("<div></div>").attr("tabIndex",-1).addClass("simplemodal-wrap").css({height:"100%",outline:0,width:"100%"}).appendTo(b.d.container);b.d.data=a.attr("id",a.attr("id")||b.o.dataId).addClass("simplemodal-data").css(d.extend(b.o.dataCss,{display:"none"})).appendTo("body");b.setContainerDimensions();b.d.data.appendTo(b.d.wrap);if(k||l)b.fixIE()},bindEvents:function(){var a=this;d("."+a.o.closeClass).bind("click.simplemodal",function(b){b.preventDefault();a.close()});
a.o.modal&&a.o.close&&a.o.overlayClose&&a.d.overlay.bind("click.simplemodal",function(b){b.preventDefault();a.close()});d(document).bind("keydown.simplemodal",function(b){if(a.o.modal&&b.keyCode===9)a.watchTab(b);else if(a.o.close&&a.o.escClose&&b.keyCode===27){b.preventDefault();a.close()}});d(window).bind("resize.simplemodal",function(){f=a.getDimensions();a.o.autoResize?a.setContainerDimensions():a.o.autoPosition&&a.setPosition();if(k||l)a.fixIE();else if(a.o.modal){a.d.iframe&&a.d.iframe.css({height:f[0],
width:f[1]});a.d.overlay.css({height:f[0],width:f[1]})}})},unbindEvents:function(){d("."+this.o.closeClass).unbind("click.simplemodal");d(document).unbind("keydown.simplemodal");d(window).unbind("resize.simplemodal");this.d.overlay.unbind("click.simplemodal")},fixIE:function(){var a=this,b=a.o.position;d.each([a.d.iframe||null,!a.o.modal?null:a.d.overlay,a.d.container],function(c,h){if(h){var g=h[0].style;g.position="absolute";if(c<2){g.removeExpression("height");g.removeExpression("width");g.setExpression("height",
'document.body.scrollHeight > document.body.clientHeight ? document.body.scrollHeight : document.body.clientHeight + "px"');g.setExpression("width",'document.body.scrollWidth > document.body.clientWidth ? document.body.scrollWidth : document.body.clientWidth + "px"')}else{var e;if(b&&b.constructor===Array){c=b[0]?typeof b[0]==="number"?b[0].toString():b[0].replace(/px/,""):h.css("top").replace(/px/,"");c=c.indexOf("%")===-1?c+' + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"':
parseInt(c.replace(/%/,""))+' * ((document.documentElement.clientHeight || document.body.clientHeight) / 100) + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"';if(b[1]){e=typeof b[1]==="number"?b[1].toString():b[1].replace(/px/,"");e=e.indexOf("%")===-1?e+' + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"':parseInt(e.replace(/%/,""))+' * ((document.documentElement.clientWidth || document.body.clientWidth) / 100) + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"'}}else{c=
'(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"';e='(document.documentElement.clientWidth || document.body.clientWidth) / 2 - (this.offsetWidth / 2) + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"'}g.removeExpression("top");g.removeExpression("left");g.setExpression("top",
c);g.setExpression("left",e)}}})},focus:function(a){var b=this;a=a&&d.inArray(a,["first","last"])!==-1?a:"first";var c=d(":input:enabled:visible:"+a,b.d.wrap);setTimeout(function(){c.length>0?c.focus():b.d.wrap.focus()},10)},getDimensions:function(){var a=d(window);return[d.browser.opera&&d.browser.version>"9.5"&&d.fn.jquery<"1.3"||d.browser.opera&&d.browser.version<"9.5"&&d.fn.jquery>"1.2.6"?a[0].innerHeight:a.height(),a.width()]},getVal:function(a,b){return a?typeof a==="number"?a:a==="auto"?0:
a.indexOf("%")>0?parseInt(a.replace(/%/,""))/100*(b==="h"?f[0]:f[1]):parseInt(a.replace(/px/,"")):null},update:function(a,b){var c=this;if(!c.d.data)return false;c.d.origHeight=c.getVal(a,"h");c.d.origWidth=c.getVal(b,"w");c.d.data.hide();a&&c.d.container.css("height",a);b&&c.d.container.css("width",b);c.setContainerDimensions();c.d.data.show();c.o.focus&&c.focus();c.unbindEvents();c.bindEvents()},setContainerDimensions:function(){var a=this,b=k||m,c=a.d.origHeight?a.d.origHeight:d.browser.opera?
a.d.container.height():a.getVal(b?a.d.container[0].currentStyle.height:a.d.container.css("height"),"h");b=a.d.origWidth?a.d.origWidth:d.browser.opera?a.d.container.width():a.getVal(b?a.d.container[0].currentStyle.width:a.d.container.css("width"),"w");var h=a.d.data.outerHeight(true),g=a.d.data.outerWidth(true);a.d.origHeight=a.d.origHeight||c;a.d.origWidth=a.d.origWidth||b;var e=a.o.maxHeight?a.getVal(a.o.maxHeight,"h"):null,i=a.o.maxWidth?a.getVal(a.o.maxWidth,"w"):null;e=e&&e<f[0]?e:f[0];i=i&&i<
f[1]?i:f[1];var j=a.o.minHeight?a.getVal(a.o.minHeight,"h"):"auto";c=c?a.o.autoResize&&c>e?e:c<j?j:c:h?h>e?e:a.o.minHeight&&j!=="auto"&&h<j?j:h:j;e=a.o.minWidth?a.getVal(a.o.minWidth,"w"):"auto";b=b?a.o.autoResize&&b>i?i:b<e?e:b:g?g>i?i:a.o.minWidth&&e!=="auto"&&g<e?e:g:e;a.d.container.css({height:c,width:b});a.d.wrap.css({overflow:h>c||g>b?"auto":"visible"});a.o.autoPosition&&a.setPosition()},setPosition:function(){var a=this,b,c;b=f[0]/2-a.d.container.outerHeight(true)/2;c=f[1]/2-a.d.container.outerWidth(true)/
2;if(a.o.position&&Object.prototype.toString.call(a.o.position)==="[object Array]"){b=a.o.position[0]||b;c=a.o.position[1]||c}else{b=b;c=c}a.d.container.css({left:c,top:b})},watchTab:function(a){var b=this;if(d(a.target).parents(".simplemodal-container").length>0){b.inputs=d(":input:enabled:visible:first, :input:enabled:visible:last",b.d.data[0]);if(!a.shiftKey&&a.target===b.inputs[b.inputs.length-1]||a.shiftKey&&a.target===b.inputs[0]||b.inputs.length===0){a.preventDefault();b.focus(a.shiftKey?"last":
"first")}}else{a.preventDefault();b.focus()}},open:function(){var a=this;a.d.iframe&&a.d.iframe.show();if(d.isFunction(a.o.onOpen))a.o.onOpen.apply(a,[a.d]);else{a.d.overlay.show();a.d.container.show();a.d.data.show()}a.o.focus&&a.focus();a.bindEvents()},close:function(){var a=this;if(!a.d.data)return false;a.unbindEvents();if(d.isFunction(a.o.onClose)&&!a.occb){a.occb=true;a.o.onClose.apply(a,[a.d])}else{if(a.d.placeholder){var b=d("#simplemodal-placeholder");if(a.o.persist)b.replaceWith(a.d.data.removeClass("simplemodal-data").css("display",
a.display));else{a.d.data.hide().remove();b.replaceWith(a.d.orig)}}else a.d.data.hide().remove();a.d.container.hide().remove();a.d.overlay.hide();a.d.iframe&&a.d.iframe.hide().remove();setTimeout(function(){a.d.overlay.remove();a.d={}},10)}}}})(jQuery);

// Live Search
jQuery(function($){$.fn.quicksearch=function(target,opt){var timeout,cache,rowcache,jq_results,val='',e=this,options=$.extend({delay:100,selector:null,stripeRows:null,loader:null,noResults:'',bind:'keyup',onBefore:function(){return},onAfter:function(){return},show:function(){this.style.display=""},hide:function(){this.style.display="none"}},opt);this.go=function(){var i=0,noresults=true,vals=val.toLowerCase().split(' ');var rowcache_length=rowcache.length;for(var i=0;i<rowcache_length;i++){if(this.test(vals,cache[i])||val==""){options.show.apply(rowcache[i]);noresults=false}else{options.hide.apply(rowcache[i])}}if(noresults){this.results(false)}else{this.results(true);this.stripe()}this.loader(false);options.onAfter();return this};this.stripe=function(){if(typeof options.stripeRows==="object"&&options.stripeRows!==null){var joined=options.stripeRows.join(' ');var stripeRows_length=options.stripeRows.length;jq_results.not(':hidden').each(function(i){$(this).removeClass(joined).addClass(options.stripeRows[i%stripeRows_length])})}return this};this.strip_html=function(input){var output=input.replace(new RegExp('<[^<]+\>','g'),"");output=$.trim(output.toLowerCase());return output};this.results=function(bool){if(typeof options.noResults==="string"&&options.noResults!==""){if(bool){$(options.noResults).hide()}else{$(options.noResults).show()}}return this};this.loader=function(bool){if(typeof options.loader==="string"&&options.loader!==""){(bool)?$(options.loader).show():$(options.loader).hide()}return this};this.test=function(vals,t){for(var i=0;i<vals.length;i+=1){if(t.indexOf(vals[i])===-1){return false}}return true};this.cache=function(){jq_results=$(target);if(typeof options.noResults==="string"&&options.noResults!==""){jq_results=jq_results.not(options.noResults)}var t=(typeof options.selector==="string")?jq_results.find(options.selector):$(target).not(options.noResults);cache=t.map(function(){return e.strip_html(this.innerHTML)});rowcache=jq_results.map(function(){return this});return this.go()};this.trigger=function(){this.loader(true);options.onBefore();window.clearTimeout(timeout);timeout=window.setTimeout(function(){e.go()},options.delay);return this};this.cache();this.results(true);this.stripe();this.loader(false);return this.each(function(){$(this).bind(options.bind,function(){val=$(this).val();e.trigger()})})}});

// Labelify
jQuery.fn.labelify=function(settings){settings=jQuery.extend({text:"title",labelledClass:""},settings);var lookups={title:function(input){return $(input).attr("title")},label:function(input){return $("label[for="+input.id+"]").text()}};var lookup;var jQuery_labellified_elements=$(this);return $(this).each(function(){if(typeof settings.text==="string"){lookup=lookups[settings.text]}else{lookup=settings.text};if(typeof lookup!=="function"){return}var lookupval=lookup(this);if(!lookupval){return}$(this).data("label",lookup(this).replace(/\n/g,''));$(this).focus(function(){if(this.value===$(this).data("label")){this.value=this.defaultValue;$(this).removeClass(settings.labelledClass)}}).blur(function(){if(this.value===this.defaultValue){this.value=$(this).data("label");$(this).addClass(settings.labelledClass)}});var removeValuesOnExit=function(){jQuery_labellified_elements.each(function(){if(this.value===$(this).data("label")){this.value=this.defaultValue;$(this).removeClass(settings.labelledClass)}})};$(this).parents("form").submit(removeValuesOnExit);$(window).unload(removeValuesOnExit);if(this.value!==this.defaultValue){return}this.value=$(this).data("label");$(this).addClass(settings.labelledClass)})};

// Tolltips
(function($){$.fn.tipsy=function(options){options=$.extend({},$.fn.tipsy.defaults,options);return this.each(function(){var opts=$.fn.tipsy.elementOptions(this,options);$(this).hover(function(){$.data(this,'cancel.tipsy',true);var tip=$.data(this,'active.tipsy');if(!tip){tip=$('<div class="tipsy"><div class="tipsy-inner"/></div>');tip.css({position:'absolute',zIndex:100000});$.data(this,'active.tipsy',tip)}if($(this).attr('title')||typeof($(this).attr('original-title'))!='string'){$(this).attr('original-title',$(this).attr('title')||'').removeAttr('title')}var title;if(typeof opts.title=='string'){title=$(this).attr(opts.title=='title'?'original-title':opts.title)}else if(typeof opts.title=='function'){title=opts.title.call(this)}tip.find('.tipsy-inner')[opts.html?'html':'text'](title||opts.fallback);var pos=$.extend({},$(this).offset(),{width:this.offsetWidth,height:this.offsetHeight});tip.get(0).className='tipsy';tip.remove().css({top:0,left:0,visibility:'hidden',display:'block'}).appendTo(document.body);var actualWidth=tip[0].offsetWidth,actualHeight=tip[0].offsetHeight;var gravity=(typeof opts.gravity=='function')?opts.gravity.call(this):opts.gravity;switch(gravity.charAt(0)){case'n':tip.css({top:pos.top+pos.height,left:pos.left+pos.width/2-actualWidth/2}).addClass('tipsy-north');break;case's':tip.css({top:pos.top-actualHeight,left:pos.left+pos.width/2-actualWidth/2}).addClass('tipsy-south');break;case'e':tip.css({top:pos.top+pos.height/2-actualHeight/2,left:pos.left-actualWidth}).addClass('tipsy-east');break;case'w':tip.css({top:pos.top+pos.height/2-actualHeight/2,left:pos.left+pos.width}).addClass('tipsy-west');break}if(opts.fade){tip.css({opacity:0,display:'block',visibility:'visible'}).animate({opacity:0.8})}else{tip.css({visibility:'visible'})}},function(){$.data(this,'cancel.tipsy',false);var self=this;setTimeout(function(){if($.data(this,'cancel.tipsy'))return;var tip=$.data(self,'active.tipsy');if(opts.fade){tip.stop().fadeOut(function(){$(this).remove()})}else{tip.remove()}},100)})})};$.fn.tipsy.elementOptions=function(ele,options){return $.metadata?$.extend({},options,$(ele).metadata()):options};$.fn.tipsy.defaults={fade:false,fallback:'',gravity:'n',html:false,title:'title'};$.fn.tipsy.autoNS=function(){return $(this).offset().top>($(document).scrollTop()+$(window).height()/2)?'s':'n'};$.fn.tipsy.autoWE=function(){return $(this).offset().left>($(document).scrollLeft()+$(window).width()/2)?'e':'w'}})(jQuery);

//Countdown
jQuery.fn.countdown=function(d){var e={stepTime:60,format:"dd:hh:mm:ss",startTime:"01:12:32:55",digitImages:6,digitWidth:53,digitHeight:77,timerEnd:function(){},image:"digits.png"};var f=[],interval;var g=function(a){var c=0;for(var i=0;i<e.startTime.length;i++){if(parseInt(e.startTime[i])>=0){elem=$('<div id="cnt_'+i+'" class="cntDigit" />').css({height:e.digitHeight*e.digitImages*10,float:'left',background:'url(\''+e.image+'\')',width:e.digitWidth});f.push(elem);h(c,-((parseInt(e.startTime[i])*e.digitHeight*e.digitImages)));f[c].__max=9;switch(e.format[i]){case'h':f[c].__max=(c%2==0)?2:9;if(c%2==0)f[c].__condmax=4;break;case'd':f[c].__max=9;break;case'm':case's':f[c].__max=(c%2==0)?5:9}++c}else elem=$('<div class="cntSeparator"/>').css({float:'left'}).text(e.startTime[i]);a.append(elem)}};var h=function(a,b){if(b!==undefined)return f[a].css({'marginTop':b+'px'});return parseInt(f[a].css('marginTop').replace('px',''))};var j=function(a){f[a]._digitInitial=-(f[a].__max*e.digitHeight*e.digitImages);return function _move(){mtop=h(a)+e.digitHeight;if(mtop==e.digitHeight){h(a,f[a]._digitInitial);if(a>0)j(a-1)();else{clearInterval(interval);for(var i=0;i<f.length;i++)h(i,0);e.timerEnd();return}if((a>0)&&(f[a].__condmax!==undefined)&&(f[a-1]._digitInitial==h(a-1)))h(a,-(f[a].__condmax*e.digitHeight*e.digitImages));return}h(a,mtop);if(h(a)/e.digitHeight%e.digitImages!=0)setTimeout(_move,e.stepTime);if(mtop==0)f[a].__ismax=true}};$.extend(e,d);this.css({height:e.digitHeight,overflow:'hidden'});g(this);interval=setInterval(j(f.length-1),1000)};


// Trim

function trim(string) {
	if(!string) return "";
    return string.replace(/^\s*/, "").replace(/\s*$/, "");
}
function trimBis (str)
{
     return str.replace(/^\s+|\s+$/g,'');
}

var $user = {
	select: function(node){
		$(node).toggleClass("selecteduser");
	},
	selectall: function(){
		$("#modalfriends ul li").addClass("selecteduser");
	},
	deselectall: function(){
		$(".selecteduser").removeClass("selecteduser");
	},
	sendFB: function(at) {
		var friends = [];
		var friendsname = [];
		$("#modalfacebook .selecteduser").each(function() {
			friends.push($(this).attr('userid'));
			friendsname.push($(this).attr('username').replace("\'", " "));
		});
		
		var f = friends.join(',');
		var n = friendsname.join(",");
	
		if(f.length>0){
			$.post("/~scores/invitefacebook", {data:f, token: at, names : n}, function(response) {
				//alert("start "+f.length+" "+n..length+" "+" End");
				if(response[0]=="ok"){
					if(f.search(",") !=-1)
						document.getElementById("msgfb").innerHTML= "Thank you, your invitations have been sent.";
					else 
					   	document.getElementById("msgfb").innerHTML= "Thank you, your invitation has been sent.";
			    } else if(response[0]=="nok") {
			    	var s1 = "<p>Red alert!  We couldn't complete the invite for  <br/></p>";
			    	var s2 = "<ul>"
			    	for(var i=1; i<response.length; i++) {
			    		s2 += "<li>"+response[i]+". </li>";
			    	}
			    	s2 += "</ul>";
			    	var s3 ="<p>Since you want <br/></p>";
			    	s3+="<p>to experience the greatness of Social IQ, re-invite them later!</p>";
			    	var s4 = "<ul>"
				    for(var i=1; i<response.length; i++) {
				    	s2 += "<li>"+response[i]+". </li>";
				    }
				    s4 += "</ul>";
			    	document.getElementById("msgfb").innerHTML= "issue";
			    	document.getElementById("feedback-send-fb").innerHTML  = s1+s2+s3+s4;
			    }
				// document.getElementById("lodfb").style.display="none";
				setTimeout("$popup.closesendmodal();", 3000);
				// $popup.confirm();
		}, "json");
		}else{
			document.getElementById("msgfb").innerHTML= "Start by selecting a friend to invite";
			document.getElementById("lodfb").style.display='none';
			setTimeout("$popup.closesendmodal();", 150);
			$popup.modalfacebook();
			}		
	},
	
	sendTwitter: function(id) {
		var friends = [];
		$("#modaltwitter .selecteduser").each(function() {
			friends.push($(this).attr('userid'));
		});
		
		var f = friends.join(',');
		$.post("/~scores/invitetwitter", {data:f, uid: id}, function(response) {
				$popup.closesendmodal();
				$popup.confirm();
		});		
		
	},
	fbcount: function() {
		$('.fbcount').text($('#modalfacebook .selecteduser').size() + ' selected');
	},
	twcount: function() {
		$('.twcount').text($('#modaltwitter .selecteduser').size() + ' selected');
	}
};

var $popup = {
	modal : null,
	id: null,
	modalfacebook: function(){
		modal = $("#modalfacebook").modal({containerId: "fixmodal"}); 
	},	
	sendmodal2: function(){
		modal = $("#modaltwitter").modal({containerId: "fixmodal"}); 
	},	
	sendmodal3: function(){
		modal = $("#modalclaim").modal({containerId: "fixmodal2"}); 
	},
	closesendmodal: function(){
		modal.close();
	},
	confirm: function() {
		$.modal("<div>Thank you, your invitations have been sent</div>", {containerId: "fixmodal"});
	},	
	
	modalanalytics: function() {
		modal = $("#modalanalytics").modal({containerId: "modalanalytics-w"}); 
	},
	completeregistration: function() {
		modal = $("#email-register").modal({containerId: "email-register-w"}); 
	},	
	emailregister: function() {
		modal = $("#email-register").modal({containerId: "email-register-w"}); 
	}
};

function validateEmail(email) { 
 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
 return email.match(re);
}


$(document).ready(function() {

$("form#analyticsForm input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

	$('form#analyticsForm').submit(function(e) {
		var val = $("input[type=submit][clicked=true]").attr('name');
		console.log(val);
		
		if(val === 'skip') return true;
		
		if(!validateEmail($('#modalanalytics #text').val())) {		
			$('#modalanalytics h5').text('Please enter a valid email address');
			return false;
		} else {
			return true;
		}
	});

});

$(document).ready(function() {
    $('input#s_friends_filters').quicksearch('.friends li');
    $(":text").labelify();
    // $("#summary #subscore #trust .mask3").animate({ height: "150%"}, 3000 );
    // $("#summary #subscore #connections .mask3").animate({ height: "29%"},
	// 3000 );
    // $("#summary #subscore #authority .mask3").animate({ height: "66%"}, 3000
	// );
    // Tolltips
    $('.item').tipsy({gravity: 's',fade :'in'});
    $('.unknow-user').tipsy({gravity: 's',fade :'in'});
    $('.tooltip').tipsy({gravity: 's',fade :'in'});
    
    // Influencers
    var delay = 10000;
    /*
	 * setInterval(function() {
	 * 
	 * for(var i = 0; i < 4; i++) { var last = $('.influenced li:last'); var
	 * lastContent = '<li>'+last.html()+'</li>'; last.remove();
	 * $(lastContent).hide().prependTo('.influenced ul').slideDown('normal'); } },
	 * delay);
	 */
    
    
});

function quicksearch(ind) {
	
		$.ajax({
   		    url: "/~pages/quicksearch/",
   		    type: "POST",   		
   		    data : "ind="+ind,
   		    dataType : "json",
   		    success: function(json){
			
			  var li = document.createElement('li');
	   		  li.style.display="block";
	   		  li.id="inf_"+(ind);
		   		  var ahref = document.createElement('a');
		   		  ahref.href=json.url;
				   		var img = document.createElement('img');
				   		img.setAttribute('style', "width:46px;height:46px");
				   		img.setAttribute('alt', json.name);
				   		img.src=json.avatar;
				  ahref.appendChild(img);
				  
				  var em = document.createElement('em');
				  em.setAttribute("class", "i-firstname");
		   		  var ahrefName = document.createElement('a');
		   		  ahrefName.href=json.url;
		   		  ahrefName.appendChild(document.createTextNode(json.name));
				  em.appendChild(ahrefName);
				  
				  var span = document.createElement('span');
				  span.setAttribute("class", "i-brand_name");
				  span.appendChild(document.createTextNode(json.level));

				  var strong = document.createElement('strong');
				  strong.setAttribute("class", "points");
				  strong.appendChild(document.createTextNode(json.score));
				  
				  var div = document.createElement('div');
				  div.setAttribute("class", "clearer");
				 
		      li.appendChild(ahref);
		      li.appendChild(em);
		      li.appendChild(span);
		      li.appendChild(strong);
		      li.appendChild(div);
		     
		      var i=ind-1;
		      while(lit = document.getElementById("inf_"+i)) {
		    	  i--;
		      }
		      
		      document.getElementById("inf_"+(i+1)).className="last";
		      document.getElementById("influencers_list").removeChild(document.getElementById("inf_"+(i+1)));
		      
		      document.getElementById('influencers_list').insertBefore(li, document.getElementById('inf_'+(ind-1)));
		     // document.getElementById("inf_"+(ind)).slideDown('normal');
		      
		      setTimeout("quicksearch("+(ind+1)+");", 3000);
			},
   		    error: function(data){
				
			}
   		});

 
	/*
	 * $.jsonp({ url: "/~pages/quicksearch/&callback=?", complete:
	 * function(xOptions, textStatus) { }, dataFilter : function(json) {
	 * 
	 * var last = $('.influenced li:last'); last.setAttribute('class', "");
	 * 
	 * var li = document.createElement('li'); li.setAttribute('class', "last");
	 * li.style.display="none"; var ahref = document.createElement('a');
	 * ahref.href=json.url; var img = document.createElement('img');
	 * img.setAttribute('style', "width:46px;height:46px");
	 * img.setAttribute('alt', json.name); img.src=json.avatar;
	 * ahrhef.appendChild(img);
	 * 
	 * var em = document.createElement('em'); em.setAttribute("class",
	 * "i-firstname"); em.appendChild(document.createTextNode(json.name));
	 * 
	 * var span = document.createElement('span'); span.setAttribute("class",
	 * "i-brand_name"); span.appendChild(document.createTextNode(json.level));
	 * 
	 * var strong = document.createElement('strong');
	 * strong.setAttribute("class", "points");
	 * strong.appendChild(document.createTextNode(json.score));
	 * 
	 * var div = document.createElement('div'); div.setAttribute("class",
	 * "clearer");
	 * 
	 * li.appendChild(ahref); li.appendChild(em); li.appendChild(span);
	 * li.appendChild(strong); li.appendChild(div);
	 * 
	 * $('#influencers_list').insertBefore(li, last); li..slideDown('normal'); }
	 * }); setTimeout("quicksearch();", 1000);
	 */
}

function editProfil()
{
	document.getElementById('edit-profil').style.display = 'none';
	
	document.getElementById('my-info-edit').style.display = 'none';
	document.getElementById('my-info-save').style.display = '';
}

function htmlspecialchars (string, quote_style, charset, double_encode) {
    var optTemp = 0,
        i = 0,
        noquotes = false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }

    return string;
}

function saveProfil()
{
	document.getElementById('edit-profil').style.display = '';
	document.getElementById('my-info-edit').style.display = '';
	document.getElementById('my-info-save').style.display = 'none';

	var post="a=b";


 if(document.getElementById('edit_name').value) {
	 document.getElementById('name').innerHTML=htmlspecialchars(document.getElementById('edit_name').value);
	 post='name='+htmlspecialchars(document.getElementById('edit_name').value);
			 
 }

 if(document.getElementById('edit_city').value || trim(document.getElementById('edit_city').value) == '' ) {
 	document.getElementById('city').innerHTML=htmlspecialchars(document.getElementById('edit_city').value);
 	post+='&city='+htmlspecialchars(document.getElementById('edit_city').value);
 }

 if(document.getElementById('edit_webSite').value || trim(document.getElementById('edit_webSite').value) == '' ) {
 	document.getElementById('webSite').innerHTML=htmlspecialchars(document.getElementById('edit_webSite').value);
 	post+='&webSite='+htmlspecialchars(document.getElementById('edit_webSite').value);
 }

 if(document.getElementById('edit_bio').value || trim(document.getElementById('edit_bio').value) == '' ) {
 	document.getElementById('bio').innerHTML=htmlspecialchars(document.getElementById('edit_bio').value);
 	post+='&bio='+htmlspecialchars(document.getElementById('edit_bio').value);
 }
 

 if($('#edit_email').val() != '' && validateEmail($('#edit_email').val())) {
 	$('#email').html($('#edit_email').val());
 	post+='&email='+$('#edit_email').val();
 }
 
 

 /*
	 * gender=document.getElementById('edit_gender');
	 * if(gender.options[gender.selectedIndex].value=="m" ||
	 * gender.options[gender.selectedIndex].value=="f") {
	 * if(gender.options[0].value!="m" && gender.options[0].value!="f") {
	 * gender.remove(0); }
	 * post+='&gender='+gender.options[gender.selectedIndex].value;
	 * if(gender.options[gender.selectedIndex].value=="m") {
	 * document.getElementById('gender').innerHTML="Male"; } else {
	 * document.getElementById('gender').innerHTML="Female"; } }
	 */
 $.ajax({ 
	 type: "POST", 
	 url: "/~profile/update/", 
	 async: true, 
	 dataType:"text", 
	 data: post, 
	 success: function(text){ },
	 });

}



function addTopics()
{
	var topic = document.getElementById('inputTopic').value;
	
	if(trim(topic) == null || trim(topic) == '' ) return ;
	
	var post="a=b";
	
	post+='&topic='+topic;
	
	$.ajax({ 
		  type: "POST", 
		  url: "/~brands/addTopics/", 
		  async: true,
		  dataType:"text",
		  data: post, 
		  success: function(text){ 
		   if(text != '0')
		   {
			   addElementTopics(topic,text);
			   document.getElementById('inputTopic').value = '';
		   }   
		  },
		     
		  });
	
}

function suggestBrand()
{
	var suggest = document.getElementById('inputSuggest').value;
	if(trim(suggest) == null || trim(suggest) == '' ) return ;
	var post="a=b";
	post+='&suggest='+suggest;
	$.ajax({ 
	  type: "POST", 
	  url: "/~profile/suggestBrand/", 
	  async: true,
	  dataType:"json",
	  data: post, 
	  success: function(json){ 
		  document.getElementById('inputSuggest').value = '';
		  if(json.msg == 'ok'){
			  //alert("Brand submitted for approval");
			  document.getElementById('notification').innerHTML = 'Brand submitted for approval. Thanks for the tip';
			  document.getElementById('notification').style.display = 'block';
			  document.getElementById('inputSuggest').value = '';
			  }else if (json.msg == 'nok'){
				 // alert("Check again,");
				  document.getElementById('notification').style.display = 'block';
				  document.getElementById('notification').innerHTML = 'Check again, this brand is already there';
				  document.getElementById('inputSuggest').value = '';
				  }else{
					 // alert("Oops");
					  document.getElementById('notification').style.display = 'block';
					  document.getElementById('notification').innerHTML = 'Oops! Seems like an error occured. Try again.';
					  document.getElementById('inputSuggest').value = '';
					  }
		  },
		  });
	}


function addElementTopics(topic,topicId)
{
	var newP = document.createElement('p');
	newP.id = "p"+topicId;
	newP.innerHTML = topic;
    
	var newSpan = document.createElement("span");
	newSpan.innerHTML = 'Remove';
	
    var newLink = document.createElement("a");
	newLink.href = 'javascript:void(0)';
	newLink.onclick=function(){deleteTopics(topicId,'p'+topicId)};
	

	newLink.appendChild(newSpan);
	newP.appendChild(newLink);
	
    var div = document.getElementById('topics');
    var divSep = document.getElementById('sepTopics');
    div.insertBefore(newP,divSep);
   
}

function deleteTopics(topicId,topicIdP)
{
	
    var post="a=b";
	
	post+='&topicId='+topicId;
	
	$.ajax({ 
		  type: "POST", 
		  url: "/~brands/deleteTopics/", 
		  async: true,
		  dataType:"text",
		  data: post, 
		  success: function(text){ 
		   if(text != '0')
		   {
			   $('#'+topicIdP).remove();
		   }   
		  },
		     
		  });
}

function addBrands()
{
	var brand = document.getElementById('inputBrand').value;
	
	if(trim(brand) == null || trim(brand) == '' ) return ;
	
	var post="a=b";
	
	post+='&brand='+brand;
	
	$.ajax({ 
		  type: "POST", 
		  url: "/~brands/addBrands/", 
		  async: true,
		  dataType:"json",
		  data: post, 
		  success: function(json){ 
			
		   if(json.msg == 'nok1')
		   {
// alert("brand not found");
			   document.getElementById('error').innerHTML = 'brand not found';
			   document.getElementById('error').style.display = '';
			   document.getElementById('inputBrand').value = '';
			   
		   }else if (json.msg == 'nok' )
			   {
// alert("brand already added");
			   document.getElementById('error').style.display = '';
			      document.getElementById('error').innerHTML = 'brand already added';
				   document.getElementById('inputBrand').value = '';
				   
			   }else{
				   document.getElementById('error').style.display = 'none';
				   document.getElementById('error').innerHTML = '';
				   addElementBrands(brand,json.brandId);
// addElementBrandsRank(brand,json.brandId,json.followers);
				   document.getElementById('inputBrand').value = '';
			   }
		  },
		     
		  });
	
}

function claim()
{
	var email = document.getElementById('userEmail').value;
	
	if(trim(email) == null || trim(email) == '' ) return ;
	
	var post="a=b";
	
	post+='&userEmail='+email;
	
	$.ajax({ 
		  type: "POST", 
		  url: "/~claim/send/", 
		  async: true,
		  dataType:"json",
		  data: post, 
		  success: function(json){ 
			
		   if(json.msg == 'nok1')
		   {
// alert("brand not found");
			   document.getElementById('error').innerHTML = 'brand not found';
			   document.getElementById('error').style.display = '';
			   document.getElementById('inputBrand').value = '';
			   
		   }else if (json.msg == 'nok' )
			   {
// alert("brand already added");
			   document.getElementById('error').style.display = '';
			      document.getElementById('error').innerHTML = 'brand already added';
				   document.getElementById('inputBrand').value = '';
				   
			   }else{
				   document.getElementById('error').style.display = 'none';
				   document.getElementById('error').innerHTML = '';
				   addElementBrands(brand,json.brandId);
// addElementBrandsRank(brand,json.brandId,json.followers);
				   document.getElementById('inputBrand').value = '';
			   }
		  },
		     
		  });
	
}

function addElementBrands(brand,brandId)
{
	var newP = document.createElement('p');
	newP.id = "p"+brandId;
	newP.innerHTML = brand;
    
	var newSpan = document.createElement("span");
	newSpan.innerHTML = 'Remove';
	
    var newLink = document.createElement("a");
	newLink.href = 'javascript:void(0)';
	newLink.onclick=function(){deleteBrands(brandId,'p'+brandId)};
	

	newLink.appendChild(newSpan);
	newP.appendChild(newLink);
	
    var div = document.getElementById('brands');
    var divSep = document.getElementById('sepBrands');
    div.insertBefore(newP,divSep);
   
}


function addElementBrandsRank(brand,brandId,followers)
{
	var newli = document.createElement('li');
	newli.id = "li"+brandId;
	
    
	var iconImage = document.createElement("img");
	iconImage.src = '/img/logo-apple.png';
		
	var newStrong = document.createElement("strong");
	newStrong.innerHTML = followers;
	
	newli.appendChild(iconImage);
	newli.innerHTML = brand;
	newli.appendChild(newStrong);
	
    var ul = document.getElementById('rankBrands');
    ul.appendChild(newli);
}


function deleteBrands(brandId,brandIdP)
{
	
    var post="a=b";
	
	post+='&brandId='+brandId;
	
	$.ajax({ 
		  type: "POST", 
		  url: "/~brands/deleteBrands/", 
		  async: true,
		  dataType:"text",
		  data: post, 
		  success: function(text){ 
		   if(text != '0')
		   {
			   $('#'+brandIdP).remove();
			   $('#li'+brandId).remove();
		   }   
		  },
		     
		  });
}

function inviteFriend(id)
{
    var post="a=b";
	
	post+='&id='+id; 
	
	
	$.ajax({ 
		  type: "POST", 
		  url: "/~scores/inviteFriend/", 
		  async: true,
		  dataType:"json",
		  data: post, 
		  success: function(json){ 
		
		    
		     if(json.msg == 'ok'){
		    	 
		    	 $("#invite-row-"+id).hide("blind", {}, 2000);
		    	 $("#invite-row-"+id).remove();
		    	 addElementFriend(json.id , json.name , json.avatar ); 
		    	 
		     }else
		     {
		    	 $("#invite-row-"+id).hide("blind", function() {$("#invite-row-"+id).remove()}, 2000);
		    	 addElementFriend(json.id , json.name , json.avatar ); 
		    	 
		     }	 
		
		  },
		     
		  });

}

function donothing(){
	
}

function ignoreFriend(id)
{
	document.getElementById('invite-close'+id).onclick = function(){donothing();};
	document.getElementById('invite-close'+id).setAttribute('onclick',function(){donothing();});

	
    var post="a=b";
	
	post+='&id='+id; 
	
	
	$.ajax({ 
		  type: "POST", 
		  url: "/~scores/ignoreFriend/", 
		  async: true,
		  dataType:"json",
		  data: post, 
		  success: function(json){ 
		
		     if(json.msg == 'ok'){
		    	 
		    	 
		    	 $("#invite-row-"+id).hide("blind", {}, 1000);
		    	 $("#invite-row-"+id).remove();
		    	 addElementFriend(json.id , json.name , json.avatar );
		    	 
		     }
		
		  },
		     
		  });
}

function addElementFriend(id , name , avatar)
{
	
	var newdiv1 = document.createElement('div');
	newdiv1.id = "invite-row-"+id;
	newdiv1.className = "row";
    
	var newdiv2 = document.createElement("div");
	newdiv2.className = 'invite-profile';
	
	var newImg1 = document.createElement("img");
	newImg1.src = avatar;
	
	var newSpan = document.createElement("span");
	newSpan.innerHTML = name;
	
	newdiv2.appendChild(newImg1);
	newdiv2.appendChild(newSpan);
	
	var newdiv3 = document.createElement('div');
	newdiv3.id = "div-invite-"+id;
	newdiv3.className = "invite-row";
	
	
    var newLink1 = document.createElement("a");
    newLink1.id = "invite-send";
	newLink1.href = 'javascript:void(0)';
	newLink1.onclick=function(){inviteFriend(id)};
	
	var newImg2 = document.createElement("img");
	newImg2.src = "/img/invite-send.png";
	
	newLink1.appendChild(newImg2);
	
	var newLink2 = document.createElement("a");
    newLink2.id = "invite-close"+id;
	newLink2.href = 'javascript:void(0)';
	newLink2.onclick=function(){ignoreFriend(id)};
	
	var newImg3 = document.createElement("img");
	newImg3.src = "/img/invite-close.png";
	
	newLink2.appendChild(newImg3);
	
	var space = document.createTextNode(" ");
	
	newdiv3.appendChild(newLink1);
	newdiv3.appendChild(space);
	newdiv3.appendChild(newLink2);
	
	var newdiv4 = document.createElement('div');
	newdiv4.className = "clear";

	newdiv1.appendChild(newdiv2);
	newdiv1.appendChild(newdiv3);
	newdiv1.appendChild(newdiv4);
	
	var div = document.getElementById('invite');
    div.appendChild(newdiv1);

}
function validate(formName, fields, types, messages) 
{
	var validationFailed = false;
	for (var i=0;i<fields.length;i++) {
		if(types[i]=="text") {
			if(trim(document.getElementById(fields[i]).value)=="") {
				validationFailed = true;
				document.getElementById(fields[i]).className="error-field";
			} else {
				document.getElementById(fields[i]).className="";
			}
		} else if(types[i]=="select") {
			if(document.getElementById(fields[i]).options[document.getElementById(fields[i]).selectedIndex].value=="0") {
				validationFailed = true;
				document.getElementById(fields[i]).className="error-field";
			} else {
				document.getElementById(fields[i]).className="";
			}
		} else if(types[i]=="checkbox") {
			var isOk = true;
			var j = 1;
			var isChecked = false;
			while(a =  document.getElementById(fields[i]+j)) {
				if(a.checked == true) {
					isChecked = true;
					break;
				}
				j++;
			}
			if(isChecked == false) validationFailed = true;
			if(document.getElementById("signup_industries_15")) {
				if(document.getElementById("signup_industries_15").checked == true && trim(document.getElementById("signup_other_industry_descr").value)=="") {
					validationFailed = true;
					document.getElementById("signup_other_industry_descr").className="error-field";
				} else {
					document.getElementById("signup_other_industry_descr").className="";
				}
			}
		} else if(types[i]=="radio") {
			 var radios = document[formName].elements[fields[i]];
			 if(!(document[formName].elements[0].checked==true || document[formName].elements[1].checked || document[formName].elements[2].checked)) {
				 validationFailed = true;
			 }
			  
		}
	}

	if(validationFailed) {
		document.getElementById('errorSpot').innerHTML = "Please fill in all the required fields";
		document.getElementById('errorSpot').style.display = "block";
	} else {
		document.getElementById('errorSpot').innerHTML = "";
		document.getElementById('errorSpot').style.display = "none";
		document.getElementById(formName).submit();
	}
}


