/**
 * Function for company profile
 *
 */

var CompanyProfile = new Object();
CompanyProfile.X_AJAX_INFO = 'users_change_company_profile';
CompanyProfile.initialize = function(){
	CompanyProfile.box = $('#company_profile_box');
	CompanyProfile.boxContent = $('.content', CompanyProfile.box);
	var myOpen = function(hash) {
			var section = $(hash.t).attr('rel');
			var data = {
				X_AJAX_INFO : CompanyProfile.X_AJAX_INFO,
				'section':section
			};
			$.post(location.href, data, function(data) {
				CompanyProfile.boxContent.html(data);
				hash.w.show();
				$(CompanyProfile.box).jqmAddClose($('#companyCloseButton, #closeButton', CompanyProfile.box));
				$(CompanyProfile.box).center();
				parseForms();
				$('#company_profile_form #submit',CompanyProfile.box).click(function(){
					var registerOptions = {
						url			: location.href,
						data		: {
								X_AJAX_INFO : CompanyProfile.X_AJAX_INFO, 
								'action'    : 'action_submit',
								'section'   : $(hash.t).attr('rel')},
						success		: CompanyProfile.updateCheck,
						dataType	: 'json'
						};
					$('#company_profile_form', CompanyProfile.box).ajaxSubmit(registerOptions);
					return false;
				});
				});
		};
	CompanyProfile.box.jqm({trigger: 'a.edit_profile',  overlay:0, onShow:myOpen});
	
}


CompanyProfile.updateCheck = function(data, status, form) {
	CompanyProfile.resetValidationRedStyle();
	if(data.status == 'succes')
	{
		window.location.reload();
	}
	else{
		var first = '';
		$(data.errors).each(function(){
			if(first.length == 0) {
				first = this;
			}
			$('#' + this, CompanyProfile.box).attr('style','border-color:red');
			$("label[for='" + this + "']", CompanyProfile.box).attr('style', 'color:red');
		});
		if(first.length != 0) {
			$('#' + first.toString(), CompanyProfile.box).get(0).focus();
		}
		var err_msg = $(form).append('<span id="pls_correct_errors" style="color:#f00;font-weight:normal;font-size:11px;">Please correct the errors in red and re-submit the form</span>');
		var $form_container = $('.company_profile_edit');
		var scrollPosition = $form_container.scrollTop() + $('form', $form_container).height();
		$form_container.scrollTop(scrollPosition);
	}
	return false;

}

CompanyProfile.resetValidationRedStyle = function() {
	$('#company_profile_form input').each(function() {
		$("label[for='" + this.id + "']", CompanyProfile.box).attr('style', 'color:#000');
		$('#' + this.id, CompanyProfile.box).css('border-color', '');
	});
	$('#pls_correct_errors').remove();
}

$(document).ready(function() {
	CompanyProfile.initialize(); 
});