/**
 * registration.js
 *
 * Methods for the registration proccess
 *
 * @author     Daniel Z
 * @copyright  2007 Comet Information Systems Ltd, All Rights Reserved.
 * @requires   common.js
 * @requires   prototype.js
 */

var SERVER_ERRORS = new Array();
var TOPICS = new Array();

function init(stepId) {
    cfv.config({fail:cfv.failHandler,failMessageHandler : showError})
    switch(stepId){
        case 1:
            cfv.add('reg_username', ['blur'], ['not_empty','is_alphanumeric','is_length', 4, 15], {messages:"User name should be 4-15 letters or numbers"});
            cfv.add('reg_username', ['click'], ['not_empty','is_length', 4, 15], {messages:"User name should be 4-15 letters or numbers",element:"chkBtn"});
            cfv.add('reg_mail', ['blur'], ['not_empty','is_email'], {messages:"Please enter a valid email"});
            cfv.add('bd_year', [''], ['is_select_date','bd_day','bd_month','bd_year'], {messages:"Please enter a valid date"});
            cfv.add('reg_pass', ['blur'], ['not_empty','is_length', 6, 12], {messages:"Password should be 6 to 12 characters"});
            cfv.add('reg_pass2', ['blur'], ['is_compare','reg_pass'], {messages:"Passwords do not match"});
            cfv.add('captcha', ['blur'], ['not_empty'], {messages:"Please type the text here"});
            cfv.add('terms', ['submit'], ['is_checked'], {messages:"You must agree to Terms and Conditions"});
            break;
        case 2:
            cfv.add('reg_fname', ['blur'], ['not_empty'], {messages:"Please provide your first name"});
            cfv.add('reg_fname', ['blur'], ['is_alpha'], {messages:"First name should be letters only"});
            cfv.add('reg_lname', ['blur'], ['not_empty'], {messages:"Please provide your last name"});
            cfv.add('reg_lname', ['blur'], ['is_alpha'], {messages:"Last name should be letters only"});
            break;
        case 3:
            cfv.add('occupation', ['blur'], ['is_custom',isOptionSelected], {messages:"Please select an occupation"});
            cfv.add('company', ['blur'], ['not_empty'], {messages:"Please provide company name"});
            cfv.add('position', ['blur'], ['not_empty'], {messages:"Please provide your position"});
            cfv.add('seniority', ['blur'], ['is_custom',isOptionSelected], {messages:"Please select seniority"});
            cfv.add('captcha', ['blur'], ['not_empty'], {messages:"Please type the text here"});
            cfv.add('terms', ['submit'], ['is_checked'], {messages:"You must agree to Terms and Conditions"});            
            break;

    }
    for (var i = 0; i < SERVER_ERRORS.length; i++) {
		showError(SERVER_ERRORS[i].id, SERVER_ERRORS[i].err);
	}
}


function finishStep1(userType){
    if(validate()){
        var tags = gebi('blog_tags').value.split(",");
        if (tags.length > 5){
            showError(gebi('blog_tags'), "Please choose upto 5 tags");
        }else{
            gebi('regForm').submit();
        }
    }
}

function finishStep2(userType){
    if (validate()) {
        var frm = document.getElementById("frm");
        frm.action = "/register/index/step2?type="+userType;
        frm.submit();
    }
}

//todo doc
function checkAvailability(id) {
	//
	var username = gebi(id).value;
	var res = cfv.validateSpecific(id);
	if (res !== true) {
		showError(id,"User name should be 4-15 letters or numbers");
		return;
	}

	// Send request
	new Ajax.Request('/user/index/checkAvailability', {
		method:'get',
		parameters: "username=" + username,
		onException:generalAJAXFailure,
		onFailure:generalAJAXFailure,
		onSuccess: function(response) {
			//Eval JSON
			var json = response.responseText.evalJSON();

			//
			if (json.available) showError('reg_username', 'Username is available', 'infoBubble');
			else showError('reg_username', 'User name is taken. Please choose another one');
		}
	});
}

//todo doc
function countrySelected(id) {
	if (id == 231) gebi('state').disabled = '';
	else {
		gebi('state').disabled = 'disabled';
		gebi('state').selectedIndex = 0;
	}
}

//todo doc
var registrationTags = new Array();

//todo doc
Array.prototype.removeArrayElementByValue = function(val) {
	for (var i = 0; i < this.length; i++)
		if (this[i] == val) this.splice(i, 1);
}

//todo doc
function registerSelectTag(elem) {
    var tagsInput = gebi('blog_tags');
    var tagText = elem.innerHTML;

    if (elem.className == 'selected') {
        elem.className = '';
        registrationTags.removeArrayElementByValue(tagText);
    } else if (registrationTags.length < 3) {
        elem.className = 'selected';
        var addon;

        registrationTags.push(tagText)
    }
    registerUpdateSelectedTags();
}


//todo doc
function registerFormatTags() {
	registrationTags = gebi('blog_tags').value.split(',');
	var registrationTagsFormatted = new Array();
	for (var i = 0; i < registrationTags.length; i++) {
		var trimmed = registrationTags[i].trim();
		if (trimmed.length > 0) registrationTagsFormatted.push(trimmed);
	}

	registrationTags = registrationTagsFormatted;

	registerUpdateSelectedTags();

}

function registerUpdateSelectedTags() {
	gebi('blog_tags').value = registrationTags.join(', ');
}

var gNumOfAuthors = 1;
function addMore() {
    if (gNumOfAuthors < 10){
        var i = document.createElement("input");
        i.type = "text";
        i.className = "txtInp narrow";
        i.name = "authors[]";
        var l = document.createElement("label");
        l.className = "txtLbl";
        l.innerHTML = "Blog co-writers:";

        var b = document.createElement("br");
        gebi("moreCoWriters").appendChild(l);
        gebi("moreCoWriters").appendChild(i);
        gebi("moreCoWriters").appendChild(b);

        gNumOfAuthors++;
    }
}

function isTopicChosen() {
	var container = gebi("blog_topics");
	var inputs = container.getElementsByTagName("input");
	var res = false;
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].checked) {
			res = true;
			break;
		}
	}
	return res;
}

function filterTags(obj){
    if(obj.checked){
        TOPICS.push(obj.value);
    }else{
        TOPICS.splice(TOPICS.indexOf(obj.value),1);
    }

    new Ajax.Updater("tagCloud", "/user/registration/getTags", {
        parameters: "topic_ids=" + TOPICS,
        method:"get"
    });
}