/**
 *  partner registration page js
 * 
 */



/**
 * check reg form
 * 
 * Iterate form fields and evaluate on user submit click.
 * Start asynchronous duplicate checks on fields username and email.
 * 
 */
function zjsCheckRegFormPartner() {

	$('s').setProperty( 'disabled', 'disabled' ).addClass( 'disabled' );
	var result = new Array();
	var vLen = validRulesPartner.length;
	for (n=0; n<vLen; n++) {
		vObj = new Validation (validRulesPartner[n].id, validRulesPartner[n].fn, validRulesPartner[n].params);
		$(validRulesPartner[n].id).fireEvent('validate');
		var label = $(validRulesPartner[n].id);
		if ( vObj.result.valid==false ) {
			vObj.result.id = validRulesPartner[n].id;
			result.include( vObj.result );
			if( $defined(label) ){
				if( label.get( 'type' ) != 'checkbox' ) {
					label.addClass('error');
					label.setStyle( 'background', '#F5CACA' );
				} else {
					label.getParent().addClass( 'error' );
				}
			}
			if( $defined( $( validRulesPartner[n].id + 'Tooltip' ) ) ) {
				$( validRulesPartner[n].id + '_msg' ).set( 'html', vObj.result.msg );
				$( validRulesPartner[n].id + 'Tooltip' ).removeClass( 'field_msg' );
				$( validRulesPartner[n].id + 'Tooltip' ).addClass( 'field_msg_error' );
			}
		}
		else {
			if( $defined(label) ){
				if( label.get( 'type' ) != 'checkbox' ) {
					label.removeClass('error');
				} else {
					label.getParent().removeClass( 'error' );
				}
			}
			if( $defined( $( validRulesPartner[n].id + 'Tooltip' ) ) ) {
				$( validRulesPartner[n].id + 'Tooltip' ).removeClass( 'field_msg_error' );
				$( validRulesPartner[n].id + 'Tooltip' ).addClass( 'field_msg' );
			}
		}
	}
	var debug = false;
	if( debug ){
		zjsOwnershipConfirm();
	}
	else if ( result.length > 0 ) {
		var notif = '<div class="notify_error">';
		notif = notif + 'Something was wrong. Please check the marked fields and make the necessary corrections.' + '</div>';
		$('reg_div_notify').setProperty('html', notif);
		ZJSscrollWindow($('reg_div_notify'));
		$('s').removeProperty( 'disabled' ).removeClass( 'disabled' );
	}
	else {
		$('reg_div_notify').setProperty('html', '');
		// do extra synchronous duplicate check on fields username and email
		var uname_available = zjsCheckUsernameAvailability( $('r_username'), false);
		var email_available = zjsCheckEmailAvailability( $('r_mail_1'), false);
		if( uname_available==false || email_available==false ){
			$('s').removeProperty( 'disabled' ).removeClass( 'disabled' );
		}
		else{
			/*$('register_partner').submit();*/
			return true;
		}
	}
	return false;
}

function zjsSwitchActiveMenu(element) {
	if( element != 'bottomMenuElement' ) {
		$('activeIndicator').setStyle( 'visibility', 'visible' );
		$('activeIndicator').setStyle( 'top', ($(element).getPosition().y - $( 'proRegMenu' ).getPosition().y - 6) );
		if( !$(element).hasClass('active') ){
			activeProMenu.removeClass( 'active' );
			$(element).addClass( 'active' );
			activeProMenu = $(element);
		}
	} else {
		activeProMenu.removeClass( 'active' );
		activeProMenu = $(element);
		$('activeIndicator').setStyle( 'visibility', 'hidden' );
	}
}



function zjsOwnershipConfirm(){
	
	$('register_partner').submit();
	
	/*zjsOwnershipConfirmClose();
	return true;*/
	
	/*
	var options = {	handler: 'adopt',
					closable: false,
					closeBtn: false,
					size:{x:578,y:'auto'}
				};
	SqueezeBox.fromElement($('confirm_dialogue'), options);

	$('sbox-btn-close').dispose();
	*/
}


/* workaround for ie6 */
function zjsOwnershipConfirmClose(){
	setTimeout("$('register_partner').submit();", 50);
}


/**
 * Check if a username is available
 * 
 * @param string field The form input field id
 * @param boolean async Set this to true for normal ajax behaviour
 * @return boolean status Valid reply status if using !async
 * 
 */
function zjsCheckUsernameAvailability( field, async ){
	
	var val = field.value;
	var info = $( field ).getPrevious();
	var label = $( field ).getParent().getPrevious();
	
	var status = null;
	
	var req = new Request({
		url: '/ajax/ajax-register.php',
		method: 'post',
		data:  "field=" + field.id + "&username="+val,
		link: 'ignore',
		async: async,
		
		onSuccess: function( txt ){
			var res = JSON.decode(txt);
			if( res.result ){
				
				// Change from default state to error state on tooltip
				info.removeClass('field_msg');
				info.addClass('field_msg_error');
				
				info.setStyles( {'opacity': '0', 'display': 'block'} );
				var suggestion = '<a href="javascript:void(0);" class="ident" style="color:#ccc;" onclick="zjsPutFieldValue(\''
													+res.data[0]+'\',\''+res.field+'\');">'+res.data[0]+'</a>';
				
				info.set('html', '<span class="message">Username taken. We suggest: ' + suggestion + '</span><span class="arrow"></span>');
				status = false;
				
				// Error state on field
				field.addClass( 'error' );
				field.setStyle( 'background', '#F5CACA' );
			}
			else{
				status = true;
			}
		}
	});

	req.send();
	return status;

}


/**
 * Enter a form value and do effects
 */
function zjsPutFieldValue(val, field) {
	$('r_username').value = val;
	var label = $( field );
	if( $defined(label) ){
		label.removeClass('error');
	}
	var info = $( field ).getPrevious();
	info.fade( 'out' );
	zjsResetTooltip(label, label.id + 'Tooltip');
}



/**
 * Check if a username is available
 * 
 * @param string field The form input field id
 * @param boolean async Set this to true for normal ajax behaviour
 * @return boolean status Valid reply status if using !async
 * 
 */
function zjsCheckEmailAvailability( field, async ){
	
	var val = field.value;
	var info = $( field ).getPrevious();
	var label = $( field ).getParent().getPrevious();
	var status = null;
	
	var req = new Request({
		url: '/ajax/ajax-register.php',
		method: 'post',
		data: "email="+escape(val),
		link: 'ignore',
		async: async,
		
		onSuccess: function( txt ){
			var res = JSON.decode(txt);
			if( !res.result ){
				if( $defined( label ) ){
					label.addClass('formError');
				}
				$(info).fade('in');
				info.setProperty('html', 'E-mail is registered');
				status = false;
			}
			else{
				status = true;
			}
		}
	});
	req.send();
	return status;
}


	
/* for undo */
var myspacedata = new Hash({});

/**
 * 
 */
function zjsGetMSData( user, async ){
	
	//strip whitespace
	user = user.replace(/^\s+|\s+$/g, '');
	
	if( user == '' ){
		$('msimportbutton').blur();
		return false;
	}
	
	if(!$defined(async)) { async = true; }
	var status = null;
	
	$('msimportbutton').setProperty('disabled', 'disabled');
	$('msimportbutton').blur();
	$('import_active').addClass('activeAjaxButton');
	$('import_active').setStyle('visibility','visible');
	
	var req = new Request({
		url: '/ajax/ajax-get-myspace-data.php',
		method: 'post',
		data: "user="+escape(user),
		link: 'ignore',
		async: async,
		
		onSuccess: function( txt ){
			
			$('reg_div_notify').setProperty('html', '');

			var res = JSON.decode(txt);
			$('msimportbutton').removeProperty('disabled');
			$('import_active').setStyle('visibility','hidden');

			if( !res.success ){
				status = false;
				$('myspaceinput').setStyle('display','none');
				$('myspaceinput_error').setStyle('display','block');
			}
			else{
				
				$('myspaceinput').setStyle('display','none');
				$('myspaceinput_done').setStyle('display','block');
				
				status = true;
				var el = null;
				
				if( $chk(res.data.hometown) ){
					el = $('txt_hometown');
					myspacedata.extend( {txt_hometown: el.value} );
					el.set('value', res.data.hometown);
					zjsHighlightBckgr( el );
				}
				if( $chk(res.data.genre) ){
					var genres = $$( '#lst_genre option' );
					$each( genres, function(g, i){
	   					if( g.get('text')==res.data.genre ){
	   						myspacedata.extend( {lst_genre: $( 'lst_genre' ).selectedIndex} );
	   						$( 'lst_genre' ).selectedIndex = i;
	   						zjsHighlightBckgr( $( 'lst_genre' ) );
	   					}
   					});
				}
				if( $chk(res.data.url) ){
					el = $('txt_url');
					myspacedata.extend( {txt_url: el.value} );
					el.set('value', res.data.url);
					zjsHighlightBckgr( el );
				}
				if( $chk(res.data.artist_name) ){
					el = $('txt_artistname');
					myspacedata.extend( {txt_artistname: el.value} );
					el.set('value', res.data.artist_name);
					zjsHighlightBckgr( el );
				}
				if( $chk(res.data.edit_box) ){
					//console.log(res.data.edit_box);
					el = $('zeditor');
					myspacedata.extend( {zeditor: el.value} );
					el.set('value', res.data.edit_box);
					zjsHighlightBckgr( el );
				}
			}
		}
	});
	
	req.send();
	
	return status;
	
}



function zjsMSImportUndo(){
	//console.log($('msArrowToggle'));
	//$('msArrowToggle').setStyle('background-position','center top');
}

function zjsMSImportUndo(){
	myspacedata.each( function( value, key ){
		$(key).set('value', value);
		zjsHighlightBckgr( key );
	});
	myspacedata.empty();
	$('myspaceinput_done').setStyle('display','none');
	$('myspaceinput').setStyle('display','block');	
	$('myspacetoggler').fireEvent( 'click' );
}



function zjsMSImportRedo(){
	if( $defined('myspaceinput_error') ){
		$('myspaceinput_error').setStyle('display','none');
	}
	$('myspaceuser').set('value', '');
	$('myspaceinput').setStyle('display','block');
	$('myspaceinput_done').setStyle('display','none');
}


/**
 * Preview bbcode parsed contents of about_me field
 *
 */
function zjsPreviewAboutMe(){
	var txt_about_me = $('zeditor').get('value');
	if( txt_about_me == '' ){
		return;
	}
	var req = new Request({
		url: '/ajax/ajax-preview-about-me.php',
		method: 'post',
		data: "txt="+escape(txt_about_me),
		link: 'ignore',
		onSuccess: function( txt ){
			
			var res = JSON.decode(txt);
			
			if( res.success && $chk(res.preview) ){
				var options = {	handler: 'adopt',size:{x:700,y:'auto'} };
				/* workaround for IE: populate dom with lb contents first */
				var el = new Element( 'div', { html : res.preview, id: 'preview_about_me_lb' } );
				$('reg_confirm_txt').adopt(el);
				SqueezeBox.fromElement($('preview_about_me_lb'), options);
			}
			else{
				//error
			}
		}
	});
	req.send();
}




/**
 * flash yellow background on element
 * 
 * @param el element or id of element to highlight
 * 
 */
function zjsHighlightBckgr ( el ){
	el = $(el);
	var morpher = new Fx.Morph( el, {link:"chain", fps:"50", duration: "800"} );
	morpher.start( {"background-color": ["#ffffcc"] } );
	morpher.start( {"background-color": ["#ffffcc"] } );
	morpher.start( {"background-color": ["#ffffff"] } );
}



function zjsMsToggle(foo){
	foo.toggle();
	$('mstoggler').toggleClass('toggle_d');
	$('mstoggler').toggleClass('toggle_u');
}






/* Utils section ************************************************/



/**
*	Validation
*/
// associate the field ids with the functions and parameters for validation 
var validRulesPartner = [
                    {"id":"r_account_type",	"fn":"checkSelectValue","params":",0,'Specify your artist type.'"},
                    {"id":"r_username",		"fn":"checkUsername",	"params":",5,14,true"},
					{"id":"r_mail_1",		"fn":"checkEmail",		"params":",true"},
					//{"id":"r_country",		"fn":"checkSelectValue","params":",0,'Specify your country.'"},
					{"id":"r_password",		"fn":"checkPassword",	"params":",null,4,9"},
					{"id":"r_password_2",	"fn":"checkPassword",	"params":",$('r_password'),4,9"},
					{"id":"r_tos_id",		"fn":"checkCheckbox",	"params":",'Terms of service: confirm your consent.'"}
				 ];



//assign the rules to their respective fields (for individual calls - e.i. onblur)
function ZJSassignRulesPartner () {
	var vLen = validRulesPartner.length;
	for (y=0; y<vLen; y++) {
		$(validRulesPartner[y].id).vRules = validRulesPartner[y];
	}
}


var Validation = new Class ({

	initialize: function (field, event, params) {
		this.result = {"msg":"", "valid":true};
		add_event = eval('this.'+event+'($(field)'+params+')');
		$(field).addEvents( {
			'validate': function () { add_event }
		} );
	},

	checkUsername: function (field, min, max, async_validate) {
		var info = $( field ).getPrevious();
		info.fade( 'out' );
		var val = field.value;
		if (val == ""){
			this.result = {"msg":"Pick a username","valid":false};
		}
		else if ( (val.length < min) || (val.length > max) || (!isValid(val,ac_lwr+ac_numb+ac_upr)) ) {
			this.result = {"msg":"Min. 5 characters, no symbols, no spaces","valid":false};
		}
		else if( $defined(async_validate) ){
			zjsCheckUsernameAvailability(field, true);
		}
		return this.result;
	},

	checkEmail: function (field, async_validate) {
		var val = field.value;
		var emailFilter=/^.+@.+\..{2,4}$/;
		var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]\ ]/
		var info = $( field ).getPrevious();
		info.fade( 'out' );
		
		if ( val=="" ) {
			this.result = {"msg":"Specify your e-mail address", "valid":false};
		}
		else if ( !emailFilter.test(val) ) { 
			this.result = {"msg":"Enter a valid e-mail address", "valid":false};
		}
		else if (val.match(illegalChars)) {
			this.result = {"msg":"The e-mail address contains illegal characters.", "valid":false};
		}
		else if( $defined( async_validate ) ){
			zjsCheckEmailAvailability(field, true);
		}
		return this.result;
	},

	checkDOB: function (field) {
		var is_date =  true;
		var parent = field.getParent();
		parent.getChildren().each( function(el) {
			if (el.value == 0) {
				is_date = false;
			}
		});
		
		if ( !(is_date) ) {
			this.result = {"msg":"Specify your date of birth.","valid":false};
		}
		else if ( ! ZJSIsDate(parent.childNodes[3].value, parent.childNodes[1].value, parent.childNodes[2].value)) {
			this.result = {"msg":"Date of birth: Enter a valid date.","valid":false};
		}
		return this.result;
	},

	checkPassword: function (field, field2, min, max) {
		var val1 = field.value;
		var val2 = null;
		if (field2 != null) {
			val2 = field2.value;
		}

		if (val1 == "" && val2 == null) return this.result = {"msg":"Specify your password","valid":false};

		if ( (val2 != null && val1 != val2) || (val2 == '' && val1 == '') ) {
			return this.result = {"msg":"Passwords doesn\'t match","valid":false};
		}

		if ((val1.length < min) || (val1.length > max) || (!isValid(val1,ac_lwr+ac_numb)) ) {
			return this.result = {"msg":"Min. 4  characters, no symbols, spaces or caps","valid":false};
		}
	},

	checkRadio: function (field, custom_msg) {
		var is_checked = false;
		if (field.checked) {
			is_checked = true;
		} else {
			var parent = field.getParent();
			parent.getChildren().each( function(el) {
				if (el.name == field.name && el.checked) {
					is_checked = true;
				}
			});
		}
		if ( !(is_checked) ) {
			this.result = {"msg":custom_msg,"valid":false};
		}
		return this.result;
	},

	checkSelectValue: function (field, errVal, custom_msg) {
		var val = field.value;
		if (val == errVal) {
			this.result = {"msg":custom_msg,"valid":false};
		}
		if ((field.id == 'r_phone_brand' || field.id == 'r_phone_model') && $('r_no_phonemodel').getProperty('checked')) {
			return this.result = {"msg":'',"valid":true};
		}
		return this.result;
	},

	checkCheckbox: function (field, custom_msg) {
		var is_checked = false;
		if (field.checked) {
			is_checked = true;
		}
		/*NOTE: deprecated*/
		if (field.id == 'r_no_phonemodel') {  // TO-DO: more elegant handling for phone model checkbox
			if (!is_checked) {
				$('r_phone_brand').removeProperty( 'disabled' );
				$('r_phone_model').removeProperty( 'disabled' );
				if ($('r_phone_model').value > 0) {
					return this.result = {"msg":"","valid":true};
				}
			} else {
				$('r_phone_brand').setProperty( 'disabled', 'disabled' );
				$('r_phone_model').setProperty( 'disabled', 'disabled' );
				ZJSoutputRegisterStatus('','reg_div_phonebrand','');
				is_checked = true;
			}
		}
		if ( !(is_checked) ) {
			this.result = {"msg":custom_msg,"valid":false};
		}
		return this.result;
	}

});


