/********************* BOX DI LOGIN **************************/
/* ATTENZIONE: questo js viene chiamato anche da EZ e DRESSUP e COSMOGIRL quindi toccarlo con attenzione */

function isset(varname) {
		return(typeof(window[varname])!= 'undefined');
	}
//E' necesssario dichiarare la variabile query_box_large per stabilire il tpl da usare (per dressup o cosmogirl).
// Per dressup la variabile viene dichiarata nel tpl associato. Default viene settata vuota.
if (!isset('query_box_large')) var query_box_large=''; 


jQuery(document).ready(function() {
	jQuery('.login-2011').each(function () {
		
		var amerg_cookie = getCookie('amerg_cookie');
		if ( amerg_cookie == null) {										
			jQuery.ajax({url: "http://community.cosmopolitan.it/register/widgetloginnotlogged"+query_box_large,
		        dataType: "jsonp",
				jsonp: "jsoncallback",
				timeout: 5000,
				success: function(data){
					jQuery('.login-2011').html(data.item);
					//javascript presente in community_login.js
					attivaPulsantiLogin("");
				},
				error: function(XHR, textStatus, errorThrown){
				}
			});
		} else {
			if(amerg_cookie.split('*').length > 0) {
				var nickname = amerg_cookie.split('*')[1];
				nickname = nickname.replace(/"/g,'');
				jQuery.ajax({url: "http://community.cosmopolitan.it/register/widgetloginlogged"+query_box_large,
			     	data: { "nickname" : nickname , "cookie" :
			     	getCookie('amerg_cookie') },
			        dataType: "jsonp",
				    jsonp: "jsoncallback",
				    timeout: 5000,
				    success: function(data){
				       	jQuery('.login-2011').html(data.item);
			        },
			        error: function(XHR, textStatus, errorThrown){
		        	}
				});
			}
		}
	});
	
});

function attivaPulsantiLogin(basePath) {
	//ci possono essere: edit-name o edit-username e edit-pass o edit-password
	jQuery("#linklogin,#loginbox").each(function() {
	jQuery('#scrittapwdboxlogin').click(function(){
		jQuery(this).hide();
		jQuery("#pwdboxlogin").show();
		jQuery('#edit-password').focus();
		jQuery('#edit-pass').focus();
		});
	jQuery('#scrittapwdboxlogin > input').focus(function(){
		jQuery("#scrittapwdboxlogin").hide();
		jQuery("#pwdboxlogin").show();
		jQuery('#edit-password').focus();
		jQuery('#edit-pass').focus();
		});
	jQuery('#edit-password,#edit-pass').focus(function(){
		jQuery('#scrittapwdboxlogin').hide();
		});
	jQuery('#edit-password,#edit-pass').blur(function(){
		var password =jQuery(this).val();
		if( password==null || password=='') {
			jQuery('#scrittapwdboxlogin').show();
			jQuery("#pwdboxlogin").hide();
			}});
	jQuery('#edit-username,#edit-name').val("Username");
	jQuery('#edit-username').focus(function(){var username =jQuery(this).val();if( username!=null && username=='Username'){jQuery(this).val('');}});
	jQuery('#edit-username').blur(function(){var username =jQuery(this).val();if( username==null || username==''){jQuery(this).val('Username');}});
	jQuery('#edit-name').focus(function(){var username =jQuery(this).val();if( username!=null && username=='Username'){jQuery(this).val('');}});
	jQuery('#edit-name').blur(function(){var username =jQuery(this).val();if( username==null || username==''){jQuery(this).val('Username');}});
	
	jQuery('#sbmtlogin,#edit-submit-login').click(function() {
		analyticsPush();
	});
	
	jQuery('#user-login').submit(function() {
		var urlRitorno = location.href;
		var linkCommunity = "http://community.cosmopolitan.it";
		//analyticsPush();
		jQuery.ajax({url:linkCommunity+"/register/widgetloginpost",
						data: { "name" :jQuery('#edit-name').val(),
								"password" :jQuery('#edit-pass').val(),
								"ricordami" :jQuery('#edit-salvaCookie-S').attr('checked'),
								"urlRitorno" : urlRitorno
					},
					dataType: "jsonp",
					jsonp: "jsoncallback",
					timeout: 10000,
					success: function(data) {
						amerg_cookie = getCookie('amerg_cookie');
						/*if (amerg_cookie == null) {
							window.location.href = linkCommunity+"/user/login";
						} else {*/
							urlRitorno = data.item;
							if ( (urlRitorno==linkCommunity) 
									|| (urlRitorno==linkCommunity+'user/login?id=error') 
									|| (urlRitorno==linkCommunity+'completa-registrazione.*/g') ) {
	                            if (amerg_cookie != null) {
	                            	
	                            	urlRitorno = linkCommunity;
	                            }
							}
							window.location.href = urlRitorno;
						//}
					},
					error: function(XHR, textStatus, errorThrown){
					}
		});
		return false;
	});
	
	jQuery('.annulla-cambia-profilo').click(function () 
	{
		location.href=basePath+"/il-tuo-profilo";
		return false;
	}
	);
	
	});

	jQuery('#registratibutton').click(function(){
		location.href=basePath+"/registrazione";
		return false;
	});

	//url di ritorno per la login esterna 
	jQuery('#user-login').each(function(){
		//solo se la destinazione non c'è già
		if (jQuery("#edit-urlRitorno").size()>0 && jQuery("#edit-urlRitorno").val().indexOf("destination=") == -1) {
			jQuery("#edit-urlRitorno").val(jQuery("#edit-urlRitorno").val()+"?destination="+URLEncode(window.location));
		}
	});
	//url di ritorno per esci
	//da fare?
	
	
}

function URLEncode (clearString) {
	  var output = '';
	  var x = 0;
	  clearString = clearString.toString();
	  var regex = /(^[a-zA-Z0-9_.]*)/;
	  while (x < clearString.length) {
	    var match = regex.exec(clearString.substr(x));
	    if (match != null && match.length > 1 && match[1] != '') {
	    	output += match[1];
	      x += match[1].length;
	    } else {
	      if (clearString[x] == ' ')
	        output += '+';
	      else {
	        var charCode = clearString.charCodeAt(x);
	        var hexVal = charCode.toString(16);
	        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
	      }
	      x++;
	    }
	  }
	  return output;
	}


function getCookie(NameOfCookie) {
	if (document.cookie.length > 0) {
		begin = document.cookie.indexOf(NameOfCookie+"=");
		if (begin != -1) {
			begin += NameOfCookie.length+1;
			end = document.cookie.indexOf(";", begin);
			if (end == -1) {end = document.cookie.length;}
				return unescape(document.cookie.substring(begin, end));
			}
	}
return null;
}







