/*
function userSignStatus(email,url) {
  $.ajax({
    url: sBasePath+'/petition/usersignstatus',
    type: 'POST',
    dataType: 'json',
    data: {'email':email,'url':url} ,
    success: function(data){
      if(typeof data.error === 'undefined'){
        if( (typeof data.status === 'number')){
          alert('user registered');
          if( (typeof data.cansign === 'number')){
            alert('user can sign');
          }
          else{
            alert('user cannot sign');
          }
alert(data.cansign);
          alert(data.status);
        }
        else{
          alert('user no registered');
        }
      }
      else{
        alert(data.error);  
      }
    },
    error: function(){
      alert('Error!');
    }
  });
}
userSignStatus('whisher@mp4.it','simonepetition');
*/

var timeout = 0;

var active_tiptip = function(elem, elId, text) {
	
	var org_title = text;
	var org_elem = elem;
	var timeout = 0;
	//var elId = elem.attr('id');
	
	if($(".tiptip_holder." + elId).length <= 0){
		var tiptip_holder = $('<div class="tiptip_holder ' + elId + '" style="max-width:200px;"></div>');
		var tiptip_content = $('<div class="tiptip_content ' + elId + '"></div>');
		var tiptip_arrow = $('<div class="tiptip_arrow ' + elId + '"></div>');
		$("body").append(tiptip_holder.html(tiptip_content).prepend(tiptip_arrow.html('<div class="tiptip_arrow_inner"></div>')));
	} else {
		var tiptip_holder = $(".tiptip_holder." + elId);
		var tiptip_content = $(".tiptip_content." + elId);
		var tiptip_arrow = $(".tiptip_arrow." + elId);
	}
	
	tiptip_content.html(org_title);
	tiptip_holder.hide()/*.removeAttr("class")*/.css("margin","0");
	tiptip_arrow.removeAttr("style");
	
	var top = parseInt(org_elem.offset()['top']);
	var left = parseInt(org_elem.offset()['left']);
	var org_width = parseInt(org_elem.outerWidth());
	var org_height = parseInt(org_elem.outerHeight());
	var tip_w = tiptip_holder.outerWidth();
	var tip_h = tiptip_holder.outerHeight();
	var w_compare = Math.round((org_width - tip_w) / 2);
	var h_compare = Math.round((org_height - tip_h) / 2);
	var marg_left = Math.round(left + w_compare);
	var marg_top = Math.round(top + org_height);
	var t_class = "";
	var arrow_top = "";
	var arrow_left = Math.round(tip_w - 12) / 2;
	
	t_class = "_top";
	
	var right_compare = (w_compare + left) < parseInt($(window).scrollLeft());
	var left_compare = (tip_w + left) > parseInt($(window).width());
	
	if((right_compare && w_compare < 0) || (t_class == "_right" && !left_compare) || (t_class == "_left" && left < (tip_w + 5))){
		t_class = "_right";
		arrow_top = Math.round(tip_h - 8) / 2;
		arrow_left = -12;
		marg_left = Math.round(left + org_width);
		marg_top = Math.round(top + h_compare);
	} else if((left_compare && w_compare < 0) || (t_class == "_left" && !right_compare)){
		t_class = "_left";
		arrow_top = Math.round(tip_h - 8) / 2;
		arrow_left =  Math.round(tip_w);
		marg_left = Math.round(left - (tip_w + 5));
		marg_top = Math.round(top + h_compare);
	}

	var top_compare = (top + org_height + tip_h + 8) > parseInt($(window).height() + $(window).scrollTop());
	var bottom_compare = ((top + org_height) - (tip_h + 8)) < 0;
	
	if(top_compare || (t_class == "_bottom" && top_compare) || (t_class == "_top" && !bottom_compare)){
		if(t_class == "_top" || t_class == "_bottom"){
			t_class = "_top";
		} else {
			t_class = t_class+"_top";
		}
		arrow_top = tip_h;
		marg_top = Math.round(top - (tip_h + 5));
	} else if(bottom_compare | (t_class == "_top" && bottom_compare) || (t_class == "_bottom" && !top_compare)){
		if(t_class == "_top" || t_class == "_bottom"){
			t_class = "_bottom";
		} else {
			t_class = t_class+"_bottom";
		}
		arrow_top = -12;
		marg_top = Math.round(top + org_height);
	}

	if(t_class == "_right_top" || t_class == "_left_top"){
		marg_top = marg_top + 5;
	} else if(t_class == "_right_bottom" || t_class == "_left_bottom"){
		marg_top = marg_top - 5;
	}
	if(t_class == "_left_top" || t_class == "_left_bottom"){
		marg_left = marg_left + 5;
	}
	tiptip_arrow.css({"margin-left": arrow_left+"px", "margin-top": arrow_top+"px"});
	tiptip_holder.css({"margin-left": marg_left+"px", "margin-top": marg_top+"px"}).addClass("tip"+t_class);
	
	//if (timeout){ clearTimeout(timeout); }
	//timeout = setTimeout(function(){ tiptip_holder.stop(true,true).fadeIn(); }, 200);
	tiptip_holder.stop(true,true).fadeIn();
};

var deactive_tiptip = function(elem, elId) {
	//var elId = elem.attr('id');
	if ($(".tiptip_holder." + elId).length >= 1) {
		var tiptip_holder = $(".tiptip_holder." + elId);
		//if (timeout){ clearTimeout(timeout); }
		tiptip_holder.hide();
	}
};

var statementEditor = null;

function  strip_tags(str, allowed_tags) {
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
    
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
    
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
    
    str += '';
    
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
        
        // Save HTML tag
        html = matches[key].toString();
        
        // Is tag not in allowed list? Remove from str!
        allowed = false;
        
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
            
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
            
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
    
    return str;
}

function trim(stringa){
	while (stringa.substring(0,1) == ' '){
		stringa = stringa.substring(1, stringa.length);
	}
	while (stringa.substring(stringa.length-1, stringa.length) == ' '){
		stringa = stringa.substring(0,stringa.length-1);
	}
	return stringa;
}

function urlLoader(sel) {
	var li = $(sel).parent().get(0);
	var loader = '<img id="urlLoader" src="'+sBasePath+'/static/images/loading.gif'+'" />';
	$(li).append(loader);
}

function hidePasswordInput(){
	$('#activationByEmail').click(function(){
		var li = $('#user_password_login').parent().get(0);
		$(li).toggle();
	});
}

function showLoader(sel) {
	var marginBottom = 30;
	var stepContainer= $(sel);
	var totHeight = $('#pagingCreatePetition').height() + stepContainer.height() + marginBottom;
	var target= $('#frmCreatePetition');
	var loader= $('<div id="loaderPetition"></div>');
	loader.fadeTo("fast", 0.9);
	loader.css({
		position: 'relative',
		width: target.width() + 'px',
		height: totHeight + 'px'
	}).hide().appendTo(target);
	loader.show();
}

function enlargeStepHeight(){
	var disclaimerH = $('#disclaimer').height();
	var stepHeaderH = $('#step6 .stepHeader').height();
	var stepSubHeaderH = $('#step6 .stepSubHeader').height();
	var h = disclaimerH + stepHeaderH + stepSubHeaderH + 50;
	$('#step6').height(h);
	$('#pagingCreatePetition').css('top',(h-35)+'px');
}

function resetPagingPos(){
	var pagingPosTop = 400;
	var $pagingCP = $('#pagingCreatePetition');
	var topPos = +$pagingCP.css('top').replace('px','');
	if(topPos > pagingPosTop){
		$pagingCP.css('top',pagingPosTop+'px');
	}
}

function xhrLogin(email,password,loginCallback){
	$.ajax({
		type: "POST",
		timeout:3000,
		url:  sBasePath + '/auth/xhr' ,
		cache: false,
		async: false,
		dataType: 'json',
		data: {'email':email,'password':password},
		success: function(data){
			loginCallback(data);
		},
		error:function(xhr, str, er){
			alert('error');
			return;
		}
	});
}

function isValidUrlXhr(slug,callback) {
	$.ajax({
		url: sBasePath + '/petition/urlavailable',
		type: 'POST',
		dataType: 'json',
		async: false,
		cache: false,
		data: {'url':slug } ,
		success: callback,
//		function(data){
//			results = callback(data);
//		},
		error: function(){
			alert('Error!');
		}
	});
}

function getUserStatus(email,callback) {
	$.ajax({
		url: sBasePath + '/petition/emailuser',
		type: 'POST',
		dataType: 'json',
		data: {'email':email} ,
		success: function(data){
			callback(data);       
		},
		error: function(){
			alert('Error!');
		}
	});
}

function isValidZipXhr(zip,callback) {
	$.ajax({
		url: sBasePath+'/petition/zipcode',
		type: 'POST',
		dataType: 'json',
		data: {'zip':zip} ,
		success: function(data){
			callback(data);
		},
		error: function(){
			alert('Error!');
		}
	});
}

function isValidLenght(str,minL,maxL){
	var l = $.trim(str).length;
	return l >= minL && l <= maxL;
}

function isValidUrl(val) {
	return /^[a-z0-9]{1}[-a-z0-9]{1,62}$/.test(val);
};

function isValidEmail(val){
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(val);
}

function isValidDigits(val) {
	return /^\d+$/.test(val);
};

function step1ValidationOld() {
	var ids = [];
	$('#category_id option').each(function(i){
		ids[i] = $(this).val();
	});
	ids.shift();
	
	var isValid = [];
	
	if (!isValidLenght($("input#title").val(),10,150)) {
		$("#title-err1").show();
	} else {
		$("#title-err1").hide();
		isValid.push(1);
	}
	
	if (!isValidLenght($("textarea#statement").val(),10,65535)) {
		$("#statement-err").show();
	} else {
		$("#statement-err").hide();
		isValid.push(1);
	}
	
	if (!in_array($("select#category_id").val(),ids)) {
		$("#category_id-err").show();
	} else {
		$("#category_id-err").hide();
		isValid.push(1);
	}
	
	return isValid.length === 3;
}

function step2ValidationOld() {
	var isValid = false;
	if (!isValidUrl($("input#url").val())) {
		$("#url-err").show();
	} else {
		$("#url-err").hide();
		isValid = true;
	}
	return isValid;
}

function step3ValidationOld() {
	var isValid = false;
	return true;
}

function step1Validation() {
	var ids = [];

	$('#category_id option').each(function(i){
		ids[i] = $(this).val();
	});
	ids.shift();
	$('.wrongExt').remove();
	var isValid = [];
	
	if ($("input#title").val() != '') {
		$("#title-err").hide();
		if (!isValidLenght($("input#title").val(),5,150)) {
			$("#title-err1").show();
			$('html, body').animate({scrollTop: $("input#title").offset().top - 30}, 700);
		} else {
			$("#title-err1").hide();
			isValid.push(1);
		}
	} else {
		$("#title-err").show();
		$("#title-err1").hide();
		$('html, body').animate({scrollTop: $("input#title").offset().top - 30}, 700);
	}
	
	var statement = trim(strip_tags(statementEditor.getHtml()));
	if (statement != '') {
		$("#statement-err").hide();
		if (!isValidLenght(statement,10,65535)) {
			$("#statement-err1").show();
			if (isValid.length == 1) {
				$('html, body').animate({scrollTop: $(".imp_redactor_box").offset().top - 25}, 700);
			}
		} else {
			$("#statement-err1").hide();
			isValid.push(1);
		}
	} else {
		$("#statement-err").show();
		$("#statement-err1").hide();
		if (isValid.length == 1) {
			$('html, body').animate({scrollTop: $(".imp_redactor_box").offset().top - 25}, 700);
		}
	}
	
	if (!in_array($("select#category_id").val(),ids)) {
		$("#category_id-err").show();
		if (isValid.length == 2) {
			$('html, body').animate({scrollTop: $("select#category_id").offset().top - 30}, 700);
		}
	} else {
		$("#category_id-err").hide();
		isValid.push(1);
	}
	
	if (!isValidUrl($("input#url").val())) {
		$("#url-err_3").hide();
		$("#url-err").show();
		if (isValid.length == 3) {
			$('html, body').animate({scrollTop: $("input#url").offset().top - 30}, 700);
		}
	} else {
		$("#url-err").hide();
		isValid.push(1);
	}
	if($('#data_treatment').length == 0){
		isValid.push(1);
	}
	else {
		if ($("#data_treatment").is(':checked')) {
			deactive_tiptip($('.prettyCheckbox .holderWrap'), 'data_treatment');
			isValid.push(1);
		} else {
			active_tiptip($('.prettyCheckbox .holderWrap'), 'data_treatment', "Devi accettare l'informativa per poter procedere");
		}
	}
	

	
	var validImageExtensions = new Array(".jpg", ".png", ".gif");
	var allowSubmit;
	$('#inputListStep3 .file').each(function(index) {
		allowSubmit = false;
		if ($('#inputListStep3 .file').eq(index).val().length>0){
		var logoImage = $('#inputListStep3 .file').eq(index).val();

			var ext = logoImage.slice(logoImage.lastIndexOf(".")).toLowerCase();
			//loop through our array of extensions
			for (var i = 0; i < validImageExtensions.length; i++) {
				if (validImageExtensions[i] == ext) {
					allowSubmit = true;
					isValid.push(1);
				}
			}
			if (allowSubmit == false) {
				$('<br/><span class="nodisplay error wrongExt"  style="display: inline;">Puoi caricare solo immagini in formato (png,gif,jpg)</span>').insertAfter($('#inputListStep3 li div').eq(index));
				$('html, body').animate({
					scrollTop: $('#inputListStep3 .file').eq(index).offset().top - 30
				}, 700);
			}
		
		
	}
	else{
			isValid.push(1);
		} 
	});	
	
	return isValid.length === 7;
}

function step2Validation() {
	var isValid = [];
	if (!isValidLenght($("input#user_firstname").val(),2,255)) {
		$("#firstname-err").show();
	} else {
		$("#firstname-err").hide();
		isValid.push(1);
	}
	
	if(!isValidLenght($("input#user_lastname").val(),2,255)) {
		$("#lastname-err").show();
	} else {
		$("#lastname-err").hide();
		isValid.push(1);
	}
	if (!isValidEmail($("input#user_email").val())) {
		$("#useremail-err").show();
	} else {
		$("#useremail-err").hide();
		isValid.push(1);
	}
	
//	if (!isValidLenght($("input#user_password").val(),1,30)) {
//		$("#password-err").show();
//	} else {
//		$("#password-err").hide();
//		isValid.push(1);
//	}
	
	if ($('#user_cellphone').hasClass('required')) {
		if (!isValidDigits($("input#user_cellphone").val())) {
			$("#cellphone-err").show();
		} else {
			$("#cellphone-err").hide();
			isValid.push(1);
		}
	} else {
		isValid.push(1);
	}
	
	if(!isValidDigits($("input#user_zip").val())) {
		$("#zip-err").show();
	} else {
		if (!isValidZipXhr(trim($("input#user_zip").val()), zipCallBack)) {
			$("#zip-err").show();
		}
		else{
			$("#zip-err").hide();
			isValid.push(1);
		}	
		
	}
	
//	if (!$("input#disclaimer").is(':checked')) {
//		$("#disclaimer-err").show();
//	} else {
//		$("#disclaimer-err").hide();
//		isValid.push(1);
//	}
	
	return isValid.length === 5;
}

function step3Validation() {
	var isValid = false;
	if (!$("input#disclaimer").is(':checked') && stepNum != 2) {
		$("#disclaimer-err").show();
	} else {
		$("#disclaimer-err").hide();
		isValid = true;
	}
	return isValid;
}

function step4Validation() {
	var isValid = false;
	return true;
}

function step5Validation() {
	var isValid = false;
	if (!isValidEmail($("input#userEmail").val())) {
		$("#useremail-err").show();
	} else {
		$("#useremail-err").hide();
		isValid = true;
	}
	return isValid;
}

function step6Validation() {
	var isValid = false;
	return true;
}

function step8Validation() {
	var isValid = [];
	if (!isValidLenght($("input#user_firstname").val(),2,255)) {
		$("#firstname-err").show();
	} else {
		$("#firstname-err").hide();
		isValid.push(1);
	}
	
	if(!isValidLenght($("input#user_lastname").val(),2,255)) {
		$("#lastname-err").show();
	} else {
		$("#lastname-err").hide();
		isValid.push(1);
	}
	if (!isValidEmail($("input#user_email").val())) {
		$("#useremail-err").show();
	} else {
		$("#useremail-err").hide();
		isValid.push(1);
	}
	
	if (!isValidLenght($("input#user_password").val(),1,30)) {
		$("#password-err").show();
	} else {
		$("#password-err").hide();
		isValid.push(1);
	}
	
	if ($('#user_cellphone').hasClass('required')) {
		if (!isValidDigits($("input#user_cellphone").val())) {
			$("#cellphone-err").show();
		} else {
			$("#cellphone-err").hide();
			isValid.push(1);
		}
	} else {
		isValid.push(1);
	}
	
	if(!isValidDigits($("input#user_zip").val())) {
		$("#zip-err").show();
	} else {
		$("#zip-err").hide();
		isValid.push(1);
	}
	
	if (!$("input#disclaimer").is(':checked')) {
		$("#disclaimer-err").show();
	} else {
		$("#disclaimer-err").hide();
		isValid.push(1);
	}
	return isValid.length === 7;
}

function step9Validation() {
	if($('#activationByEmail').is(':checked')){
		return true;
	}
	
	var isValid = [];
	if (!isValidEmail($("input#user_email_login").val())) {
		$("#login-email-err").show();
	} else {
		$("#login-email-err").hide();
		isValid.push(1);
	}
	
	if (!isValidLenght($("input#user_password_login").val(),1,30)) {
		$("#login-password-err").show();
	} else {
		$("#login-password-err").hide();
		isValid.push(1);
	}
	return isValid.length === 2;
}

function CreatePetition(){
	startNum = 1;
	//var maxNum = 6;
	var maxNum = 3;//stepNum;
	var minNum = 1;
	var fakeStep = null;
	var oddStep = false;
	

	function checkUrl(data) {
		if ($('#urlLoader').length > 0) {
			$('#urlLoader').remove();
		}
		
		if (typeof(data.url) === 'string') {
			$("#url-err_3").hide();
			if (stepNum == 2) { // if user logged
				
				$("#frmCreatePetition").unbind("submit");
				var statement = statementEditor.getHtml();
				var statement = statement.replace(/<script.*>.*<\/script>/gi, '');
				$('textarea#statement').val(statement);
				$('#frmCreatePetition').trigger("submit");
			} else {
				highlightStep();
				$('#step'+startNum).fadeOut('fast');
				forwardTab();
				$('#step'+startNum).fadeIn('slow');
				setTimeout("$('html, body').animate({scrollTop: $('#userEmail').offset().top - 200}, 700)",200);
			}
		} else {
			$("#url-err_3").show();
			$('html, body').animate({scrollTop: $("#url").offset().top - 30}, 700);
		}
	}
	
	function forwardTab() {
		if (startNum < maxNum) {
			if (stepNum == 2) {
				startNum++;
			}
			startNum++;
		} else {
			startNum = minNum;
		}
		if (startNum > 1) {
			$("#back-forward .back").removeClass('nodisplay');
			$("#btBack").removeAttr("disabled");
		}
	}
	
	function backTab() {
		if (startNum > minNum) {
			startNum--;
		}
		if (startNum === 1) {
			$("#back-forward .back").addClass('nodisplay');
		}
		
	}
	
	function highlightStep() {
		var coins = $('#create-step-numbers .coin');
		var currentItem = 0;
		for (var index = 0; index < coins.length; index++) {
			var item = coins[index];
			if ($(item).hasClass('passed')) {
				currentItem = index;
			}
		};
		$(coins[currentItem + 1]).addClass('passed');
//		$('#step .step-title-big').html(createPetitionText + ' ' + startNum + ' ' + textOf + ' ' + maxNum);
//		var stepImgPath = $('img#step'+startNum+'-img').attr('src');
//		var pathToChecked = stepImgPath.replace('check-grey'+startNum+'.jpg','check'+startNum+'.jpg'); 
//		$('img#step'+startNum+'-img').attr('src', pathToChecked);
//		$('#activeStep').text(startNum);
	}
	
	function lowlightStep(){
		var coins = $('#create-step-numbers .coin');
		var currentItem = 0;
		for (var index = 0; index < coins.length; index++) {
			var item = coins[index];
			if ($(item).hasClass('passed')) {
				currentItem = index;
			}
		};
		$(coins[currentItem]).removeClass('passed');
//		var stepImgPath = $('img#step'+startNum+'-img').attr('src');
//		var path = stepImgPath.replace('check'+startNum+'.jpg','check-grey'+startNum+'.jpg');
//		$('img#step'+startNum+'-img').attr('src', path);
//		$('#activeStep').text(startNum);
	}
	
	function lowlightTextStep() {
		$('#activeStep').text(startNum);
	}
	
	function checkLogin(data) {
		if ((typeof data.status === 'number')) {
			//showLoader('#step9');
			$('#login-password-err').hide();
			$('#registration-form').append('<input type="hidden" name="justLoggedIn" value="1"/>');
			$("#frmCreatePetition").unbind("submit");
			var statement = statementEditor.getHtml();
			var statement = statement.replace(/<script.*>.*<\/script>/gi, '');
			$('textarea#statement').val(statement);
			$('#frmCreatePetition').trigger("submit");
			
			//$('#step'+startNum).fadeOut('fast');
			//forwardTab();
			//$('#step'+startNum).fadeIn('slow');
			//highlightStep();
		} else {
//			alert('Invalid login');
//			if ($('#invLogin').length > 0) {
//				$('#invLogin').remove();
//			}
//			$("#step9 h3:first").append('<p id="invLogin">Invalid login</p>');
			$('#login-password-err').show();

		}
	}
	
	function checkRegister(data) {
		if ((typeof data.zip === 'number')) {
			$("#zip-err").hide();
			$("#frmCreatePetition").unbind("submit");
			var statement = statementEditor.getHtml();
			var statement = statement.replace(/<script.*>.*<\/script>/gi, '');
			$('textarea#statement').val(statement);
			$('#frmCreatePetition').trigger("submit");
			
			//$('#step'+startNum).fadeOut('fast');
			//forwardTab();
			//highlightStep();
			//$('#step'+startNum).fadeIn('slow');
//			$("#zip-err").hide();
//			showLoader('#step8');
//			$("#frmCreatePetition").unbind("submit");
//			$('#frmCreatePetition').trigger("submit");
		} else {
			$("#zip-err").show();
		}
	}
	
	function checkStatus(data) {
		//$('#step'+startNum).hide();
		$('#login-form').hide();
		$('#registration-form').hide();
		if ((typeof(data.status) === 'number')) {
			$('#login-form').slideDown('slow');
			//fakeStep = 9;
		} else {
			$('#registration-form').slideDown('slow');
			//fakeStep = 8;
		}
		$('#petition-login').hide();
		//$('#step'+fakeStep).show();
	}
	
	function init() {
		//stepNum;
		switch (startNum) {
			case 1:
				if (step1Validation()) {
					isValidUrlXhr($("input#url").val(), checkUrl);
				}
				break;
			case 2:
				if($("input#user_email").val().length>0 && $("input#user_email").val()!=$("input#userEmail").val()){
					$("input#userEmail").val($("input#user_email").val());
					$("input#user_email").val('');
					$("input#user_email_login").val('');
					$("div#registration-form").css({'display':'none'});
					$("div#login-form").css({'display':'none'});
					$("div#petition-login").css({'display':'block'});
				}
				if($("input#user_email_login").val().length>0 && $("input#user_email_login").val()!=$("input#userEmail").val()){
					$("input#userEmail").val($("input#user_email_login").val());
					$("input#user_email_login").val('');
					$("input#user_email").val('');
					$("div#registration-form").css({'display':'none'});
					$("div#login-form").css({'display':'none'});
					$("div#petition-login").css({'display':'block'});
				}
				if (!isValidEmail($("input#userEmail").val())) {
					$("#useremail-err").show();
				}
				else {
				
					var email = $("input#userEmail").val();
					$("input#user_email_login").val(email);
					$("input#user_email").val(email);
					
					
					if ($('#petition-login').css('display') != 'none') {
						getUserStatus(email, checkStatus);
					}
					
					if ($('#login-form').css('display') != 'none') {
					
						var email = $("input#user_email_login").val();
						if (!$('#activationByEmail').is(':checked')) {
							var password = $("input#user_password_login").val();
							xhrLogin(email, password, checkLogin);
						}
						else {
							$("#frmCreatePetition").unbind("submit");
							$('#activationByEmail').val(1);
							var statement = statementEditor.getHtml();
							var statement = statement.replace(/<script.*>.*<\/script>/gi, '');
							$('textarea#statement').val(statement);
							$('#frmCreatePetition').trigger("submit");
						}
					}
					
					if ($('#registration-form').css('display') != 'none' && step2Validation()) {
						var zip = $("input#user_zip").val();
						isValidZipXhr(zip, checkRegister);
					}
				}
				break;
			case 3:
				if (step3Validation()) {
					$("#frmCreatePetition").unbind("submit");
					var statement = statementEditor.getHtml();
					var statement = statement.replace(/<script.*>.*<\/script>/gi, '');
					$('textarea#statement').val(statement);
					$('#frmCreatePetition').trigger("submit");
				}
				break;
			case 4:
				if (step4Validation() && maxNum != startNum) {
					$('#step'+startNum).hide();
					forwardTab();
					$('#step'+startNum).show();
					highlightStep();
					$("input#userEmail").focus();
				} else if (maxNum == startNum) {
					$('#pagingCreatePetition').css({display: 'none'});
					$('#step4').css({display: 'none'});
					showLoader('#step4');
					$("#frmCreatePetition").unbind("submit");
					var statement = statementEditor.getHtml();
					var statement = statement.replace(/<script.*>.*<\/script>/gi, '');
					$('textarea#statement').val(statement);
					$('#frmCreatePetition').trigger("submit");
				}
				break;
			case 5:
				if (step5Validation() && !oddStep) {
					var email = $("input#userEmail").val();
					getUserStatus(email,checkStatus);
					$("input#user_email_login").val(email);
					$("input#user_email").val(email);
					enlargeStepHeight();
					oddStep = true;
				}
				break;
			/* case 6:
			 * 	if (step6Validation()) {
			 * 		$('#step'+startNum).hide();
			 * 		forwardTab();
			 * 		$('#step'+startNum).show();
			 * 		highlightStep();
			 * 	}
			 * 	$('#pagingCreatePetition').css('top','400px');
			 * 	break;
			 * case 7:
			 * 	if (step7Validation()) {
			 * 		var email = $("input#userEmail").val();
			 * 		getUserStatus(email,checkStatus);
			 * 		$("input#user_email_login").val(email);
			 * 		$("input#user_email").val(email);
			 * }
			 * break;*/
		}
		
		if (fakeStep === 8) {
//			$("input#userEmail").val();
//			if (step8Validation()) {
//				var zip = $("input#user_zip").val();
//				isValidZipXhr(zip,checkRegister);
//			}
		} else if (fakeStep === 9) {
			if (step9Validation()) {
				if ($('#activationByEmail').is(':checked')) {
					showLoader('#step9');
					$("#frmCreatePetition").unbind("submit");
					var statement = statementEditor.getHtml();
					var statement = statement.replace(/<script.*>.*<\/script>/gi, '');
					$('textarea#statement').val(statement);
					$('#frmCreatePetition').trigger("submit");
				} else {
					var email = $("input#user_email_login").val();
					var password = $("input#user_password_login").val();
					xhrLogin(email,password,checkLogin);
				}
			}
		}
		if (startNum > 1) {
			$("#btBack").removeAttr("disabled");
			$("#btBack").show();
		}
	}
	
	function stepBack() {
		if (startNum !== 1) {
			$('#step'+startNum).fadeOut('fast');
			backTab();
			$('#step'+startNum).fadeIn('slow');
			lowlightStep();

			$("#firstname-err").hide();
			$("#lastname-err").hide();
			$("#useremail-err").hide();
			$("#password-err").hide();
			$("#cellphone-err").hide()
			$("#zip-err").hide();
			
			$('#petition-login').show();
			$('#registration-form').hide();
			$('#login-form').hide();
		}
		
//		if (startNum === 1) {
//			$("#back-forward back").addClass('nodisplay');
//		}
	}
	
//	function stepBack() {
//		$('#step'+startNum).hide();
//		if (startNum !== 1) {
//			lowlightStep();
//		}
//		backTab();
//		lowlightTextStep();
//		$('#step'+startNum).show();
//		if (startNum === 1) {
//			$("#btBack").attr("disabled","disabled");
//			$("#btBack").hide();
//		}
//		
//		resetPagingPos();
//		if (startNum === 6) {
//			enlargeStepHeight();
//		}
//		$("#step8").hide();
//		$("#step9").hide();
//		fakeStep = null;
//		oddStep = false;
//	}
	
	$('#btNext').click(function(){
		init();
	});
	
	$('#btBack').click(function(){
		stepBack();
	});
	
//	$("input#userEmail").blur(function(){
//		if ($("input#userEmail").val()!='') {
//			if(step5Validation()){
//				init();
//			} 
//		}
//	});
	
//	if ($('#user_cellphone').hasClass('required')) {
//		var li = $('#user_cellphone').parent().get(0);
//		var label = $('label:first-child',li);
//		var labelText =  label.text();
//		$(label).html(labelText + '<span class="required">*</span>');
//	}
}
function isValidZipXhr(zip,callback) {
	var result = false;
	$.ajax({
		url: sBasePath+'/petition/zipcode',
		type: 'POST',
		timeout:3000,
		dataType: 'json',
		async: false,
		cache: false,
		data: {'zip':zip} ,
		success: function(data){
			result = callback(data);
		},
		error: function(){
			alert('Error!');
		}
	});
	return result;
	}
	
function zipCallBack(data) {
		if ((typeof data.zip === 'number')) {
			return true;
		} else {
			return false;
		}
	}

//var active_tiptip = deactive_tiptip = null;
$(document).ready(function() {
	
	$('.sfoglia.preview').click(function() {
		var url = $(this).attr('href');
		
		var title = $("input#title").val();
		var statement = statementEditor.getHtml();
		var statement = statement.replace(/<script.*>.*<\/script>/gi, '');
		var catId = $("select#category_id").val();
		if (title != '' && statement != '' && catId != 0) {
			$('#preview-err').hide();
			$.ajax({
				url: url,
				type: 'post',
				dataType: 'html',
				data: $('#frmCreatePetition').serializeArray(),
				success: function(data){
					$(document).colorbox({html:data, open: true, width: 630, height: 650, title: previewText});
				}
			});
		} else {
			$('#preview-err').show(100);
		}
		return false;
	})
	
	$('input#title').bind('keyup', function(){
		$("input#url").val(sanatizeString($("input#title").val()));
	});
	
	$('#frmCreatePetition').submit(function (){ return false; }); // so it won't submit
//	$('#extraOptionsHeader').toggle(
//		function(){
//			$('#step1-options').toggle();
//			$('#arrowextra').attr("src","/static/images/freccia-giu.gif");
//		},
//		function(){
//			$('#arrowextra').attr("src","/static/images/freccia-dx.gif");
//			$('#step1-options').toggle();              
//		}
//	);
//	
	requiredDecorator();
	CreatePetition();
	
	$("#inputListStep3 .text").filestyle({
		image: sBasePath + "/static/images/browse-"+defaultLang+".png",
		imageheight : 21,
		imagewidth : 156,
		width : 205
	});
	
	statementEditor = $('#statement').redactor({
		pathCss: '/static/js/admin/editor/css/',
		lang: 'en',
		toolbar: 'mini'
	});
	
	$('#activationByEmail').click(function(){
		var li = $('#user_password_login').parent().get(0);
		$(li).toggle();
		$('#login-password-err').hide();
		$('#user_password_login').val('');
	});
	
	/*$('input.button.accept').click(function(){
		if ($(this).is(':checked')) {
			deactive_tiptip();
			$('#btNext').removeClass('disabled');
		} else {
			$('#btNext').addClass('disabled');
		}
	});*/
	
	$("input#data_treatment").click(function(){
		if ($(this).is(':checked')) {
			deactive_tiptip($('.prettyCheckbox .holderWrap'), 'data_treatment');
			$('#btNext').removeClass('disabled');
		} else {
			$('#btNext').addClass('disabled');
		}
	});
	
	$("input#data_treatment").prettyCheckboxes({
		checkboxWidth: 28,
		checkboxHeight: 28
	});
	
	
//	$('#title').focus();
//	$("input[type=file]").filestyle({ 
//		image: sBasePath + "/static/images/btn_upload_"+defaultLang+".png",
//		imageheight : 25,
//		imagewidth : 80,
//		width : 320
//	});
//	hidePasswordInput();
//	$.datepicker.regional[defaultLang];
//	$("#expiry_date").datepicker({
//		showOn: 'button', 
//		buttonImage: sBasePath+'/static/images/datepicker.gif', 
//		buttonImageOnly: true
//	});
//	$(".explainInput").each(function(index){
//		var label = $(".explainLabel").eq(index);
//		//$('<a href="#" class="jTip" title="' + $(this).attr('title') +'">?</a>').insertBefore(label);
//		$(label).append('<a href="#" class="jTip" title="' + $(this).attr('title') +'">?</a>');
//		$(this).attr('title','');
//	});
//	
//	$('#frmCreatePetition a.jTip').tooltip({
//		track: true,
//		delay: 0,
//		showURL: false,
//		showBody: " - ",
//		extraClass: "jTipTooltip",
//		top: -15,
//		left: 5
//	});
});



