
var pdProfile = {};

pdProfile = Class.create({
    initialize: function(o){
		this.options = o || {};
		
		// Attach all event handlers
		$('p_basics_update').observe('click',this.onBasicsSaveClick.bindAsEventListener(this));
		$('p_basics_cancel').observe('click', this.onBasicsCancelClick.bindAsEventListener(this));
		$('p_personal_update').observe('click', this.onPersonalSaveClick.bindAsEventListener(this));
		$('p_personal_cancel').observe('click', this.onPersonalCancelClick.bindAsEventListener(this));
		$('p_contact_update').observe('click', this.onContactSaveClick.bindAsEventListener(this));
		$('p_contact_cancel').observe('click', this.onContactCancelClick.bindAsEventListener(this));
		$('p_login_update').observe('click', this.onLoginSaveClick.bindAsEventListener(this));
		$('p_login_cancel').observe('click', this.onLoginCancelClick.bindAsEventListener(this));		
		$('p_notifications_update').observe('click', this.onNotificationsSaveClick.bindAsEventListener(this));
		$('p_notifications_cancel').observe('click', this.onNotificationsCancelClick.bindAsEventListener(this));		
		$('p_basics').observe('click',this.onSectionClick.bindAsEventListener(this));
		$('p_personal').observe('click',this.onSectionClick.bindAsEventListener(this));
		$('p_contact').observe('click',this.onSectionClick.bindAsEventListener(this));
		$('p_sms').observe('click',this.onSectionClick.bindAsEventListener(this));
		$('p_login').observe('click',this.onSectionClick.bindAsEventListener(this));
		$('p_notifications').observe('click',this.onSectionClick.bindAsEventListener(this));
		$('p_aboutme').observe('keypress',this.limitCharacters.bindAsEventListener(this,'aboutme',2000));
		$('p_signature').observe('keypress',this.limitCharacters.bindAsEventListener(this,'signature',150));
		$('p_sendsmsverfication').observe('click',this.onSendSMSVerificationCodeClick.bindAsEventListener(this));
		$('p_setupsms').observe('click',this.onSetupSMSClick.bindAsEventListener(this));
		$('p_phonesmscarrierid').observe('change',this.onSMSChange.bindAsEventListener(this));
		$('p_phonesms').observe('focus',this.onSMSChange.bindAsEventListener(this));
		$('p_phonesmscode').observe('focus',this.onSMSChange.bindAsEventListener(this));
		
		// Bind event listeners to the phone manufacturer dropdowns
		// as well as the delete links which may be hidden at this time
		for(var x=1; x<6; x++){
			$('p_phone'+x+'_manufacturer').observe('change', this.onPhoneManufacturerChange.bindAsEventListener(this));
			$('p_phone'+x+'_delete').observe('click', this.onPersonalDeleteCommerceItemClick.bindAsEventListener(this));
		}

		
		// Configure dob menues
		var dobm=$('p_birthdatemonth');
		var dobd=$('p_birthdateday');
		var doby=$('p_birthdateyear');
		dobm.options.add(new Option('','0'));
		dobd.options.add(new Option('','0'));
		doby.options.add(new Option('','0'));
		for(var m=1;m<13;m++){dobm.options.add(new Option(m,m));}
		for(var d=1;d<32;d++){dobd.options.add(new Option(d,d));}
		for(var y=2009;y>1900;y--){doby.options.add(new Option(y,y));}  
		
		// Set the current pane equal to a possible hash in the url
		// and if none is available then default to use the basics
		this.currentPane=(self.document.location.hash=='')?'basics':self.document.location.hash.substring(1);
		this.currentPhoneElement='';
		
		// Allows us to keep track of which notifcations are clicked
		// and are supposed to be saved vs. removed 
		this.options.notificationsToAdd = [];
		this.options.notificationsToRemove = [];		
		
        // Set ajax options
        this.options.asynchronous = true;
        this.options.onSuccess = this.onSuccess.bind(this);
        this.options.onFailure = this.onFailure.bind(this);
        
        // Load the profile
        this.loadProfile();             
    },
    
    loadProfile:function(){
		this.ajaxCall='loadprofile';
		new Ajax.Request('/ajax.aspx?x=4BtwfYU1bt8%3d',this.options);
    },
    loadProfileNotifications:function(){
		this.ajaxCall='loadprofilenotifications';
		new Ajax.Request('/ajax.aspx?x=x1JDitIW9rs%3d',this.options);
    },
	onBasicsSaveClick:function(event){
		this.clearSection();

		var gendertypeid=$('p_gendertypeid');
		var genderdisplaytypeid=($('p_genderdisplaytypeid').checked)?'1':'0';
		var dobm=$('p_birthdatemonth');
		var dobd=$('p_birthdateday');
		var doby=$('p_birthdateyear');
		var dobdisplaytypeid=$('p_birthdatedisplaytypeid');
		var hometown=$('p_hometown');
		
		if(gendertypeid.value==0){this.showSaveError('Please select your gender');gendertypeid.focus();return false;}
		if(dobm.value==0){this.showSaveError('Please select your birth date month');dobm.focus();return false;}
		if(dobd.value==0){this.showSaveError('Please select your birth date day');dobd.focus();return false;}
		if(doby.value==0){this.showSaveError('Please select your birth date year');doby.focus();return false;}
		if(hometown.value==''){this.showSaveError('Please enter your hometown');hometown.focus();return false;}
        if(!$R(1,Date.getDaysInMonth(parseInt(doby.value),parseInt(dobm.value)-1)).include(dobd.value)){this.showSaveError('Invalid number of days for the given month');dobd.focus();return false;}
		
		this.ajaxCall='savebasics';
		this.options.parameters = {
			p_gendertypeid:gendertypeid.value,
			p_genderdisplaytypeid:genderdisplaytypeid,
			p_birthdate:dobm.value+'/'+dobd.value+'/'+doby.value,
			p_birthdatedisplaytypeid:dobdisplaytypeid.value,
			p_hometown:hometown.value.stripScripts().stripTags()
		}
		
		new Ajax.Request("/ajax.aspx?x=y8h50i95J8Y%3d",this.options);
	},
	
	onBasicsCancelClick:function(){this.clearSection(true);},

	onPersonalSaveClick:function(){
		this.clearSection();
		
		var aboutme=$('p_aboutme');
		var signature=$('p_signature');
		
		if(aboutme.value.strip().length>2000){this.showSaveError('Please limit your "About me" text to 2000 characters');aboutme.focus();return false;}
		if(signature.value.strip().length>150){this.showSaveError('Please limit your "Signature" text to 150 characters');signature.focus();return false;}
		
		this.ajaxCall='savepersonal';
		this.options.parameters = {
			p_aboutme:aboutme.value.stripScripts().stripTags().gsub('\n','<br/>'),
			p_signature:signature.value.stripScripts().stripTags().gsub('\n','<br/>'),
			p_phone1:$('p_phone1_model').value,
			p_phone2:$('p_phone2_model').value,
			p_phone3:$('p_phone3_model').value,
			p_phone4:$('p_phone4_model').value,
			p_phone5:$('p_phone5_model').value
		}
		
		new Ajax.Request("/ajax.aspx?x=bkSSZBrWuBI%3d",this.options);
	},
	onPersonalDeleteCommerceItemClick:function(event){
		if(confirm('Are you sure you want to remove this phone from your profile?')){
			var el=Event.element(event);
			this.currentPhoneElement=el.previous();
			this.ajaxCall='deleteitem';
			this.options.parameters={p_itemid:el.readAttribute('itemid')}
			new Ajax.Request("/ajax.aspx?x=sOqm4mcjqq0%3d",this.options);
		}
	},
	onPersonalCancelClick:function(){this.clearSection(true);},

	onContactSaveClick:function(){
		this.clearSection();
		
		var firstname=$('p_firstname');
		var lastname=$('p_lastname');		
		var email=$('p_email');
		var website=$('p_website');
		var twitter=$('p_twitter');
		
		if(firstname.value==''){this.showSaveError('Please enter your first name');firstname.focus();return false;}
		if(lastname.value==''){this.showSaveError('Please enter your last name');lastname.focus();return false;}
		if(email.value==''){this.showSaveError('Please enter your email address');email.focus();return false;}
		if(!this.isValidEmail(email.value)){this.showSaveError('Your email address appears to be invalid');email.focus();return false;}
		
		this.ajaxCall='savecontact';
		this.options.parameters = {
			p_firstname:firstname.value.stripScripts().stripTags(),
			p_lastname:lastname.value.stripScripts().stripTags(),
			p_namedisplaytypeid:$('p_namedisplaytypeid').value,
			p_email:email.value.stripScripts().stripTags(),
			p_website:website.value.stripScripts().stripTags(),
			p_twitter:twitter.value
		}
		
		new Ajax.Request("/ajax.aspx?x=AZiH1sU5k%2bw%3d",this.options);		
	},
	onContactCancelClick:function(){this.clearSection(true);},
	
	onSendSMSVerificationCodeClick:function(){
		this.clearSection();
		
		var phonesmscarrierid=$('p_phonesmscarrierid');
		var phonesms=$('p_phonesms');
		
		if(phonesmscarrierid.value==''){this.showSaveError('Please select your carrier');phonesmscarrierid.focus();return false;}
		if(phonesms.value==''){this.showSaveError('Please enter your mobile phone number');phonesms.focus();return false;}		
		
		this.ajaxCall='sendsmsverification';
		this.options.parameters = {
			p_phonesms:phonesms.value.stripScripts().stripTags(),
			p_phonesmscarrierid:phonesmscarrierid.value
		}
		new Ajax.Request("/ajax.aspx?x=EacFBU6Kl9I%3d",this.options);
	},
	onSetupSMSClick:function(){
		this.clearSection();
		var phonesmscode=$('p_phonesmscode');
		if(phonesmscode.value==''){this.showSaveError('Please enter the verification code');phonesmscode.focus();return false;}
		
		this.ajaxCall='setupsms';
		this.options.parameters = {p_phonesmscode:phonesmscode.value}
		new Ajax.Request("/ajax.aspx?x=BHafvx%2fcMg4%3d",this.options);
	},
	onSMSChange:function(){
		$('p_sendsmsverfication').disabled=false;
		$('p_setupsms').disabled=false;	
	},

	onLoginSaveClick:function(){
		this.clearSection();
		
		var username=$('p_username');
		var password=$('p_password');
		var passconfirm=$('p_passconfirm');
		
		if(username.value==''){this.showSaveError('Please enter a username');username.focus();return false;}
		if(username.value.indexOf('\'')!=-1){this.showSaveError('Username may not contain single quotes');username.focus();return false;}
		if(username.value.length<6){this.showSaveError('Your username must be at least six characters long');username.focus();return false;}
		if(password.value==''){this.showSaveError('Please enter a password');password.focus();return false;}
		if(password.value.indexOf('\'')!=-1){this.showSaveError('Password may not contain single quotes');password.focus();return false;}
		if(passconfirm.value==''){this.showSaveError('Please confirm your password');passconfirm.focus();return false;}
		if(password.value!=passconfirm.value){this.showSaveError('Your passwords don\'t match');return false;}
		if(password.value.length<6){this.showSaveError('Your password must be at least six characters long');password.focus();return false;}
		
		this.ajaxCall='savelogin';
		this.options.parameters = {
			p_username:username.value.stripScripts().stripTags(),
			p_password:password.value.stripScripts().stripTags()
		}
		
		new Ajax.Request("/ajax.aspx?x=EoeSri%2bE5RU%3d",this.options);		
	},
	onLoginCancelClick:function(){this.clearSection(true);},
	
	onNotificationsSaveClick:function(){
		this.clearSection();	
		this.ajaxCall='savenotifications';
		this.options.parameters = {
			p_notifications_addids:this.options.notificationsToAdd.toString(),
			p_notifications_removeids:this.options.notificationsToRemove.toString()
		}
		
		new Ajax.Request("/ajax.aspx?x=zLHJj4ng2Y4%3d",this.options);		
	},
	onNotificationCheck:function(event){
		var checkbox=Event.element(event);
		
		//remove the notifcation id from both the add & remove arrays
		this.options.notificationsToAdd=this.options.notificationsToAdd.without(checkbox.value);
		this.options.notificationsToRemove=this.options.notificationsToRemove.without(checkbox.value);
		
		if(checkbox.checked){
			this.options.notificationsToAdd.push(checkbox.value);
		}else{
			this.options.notificationsToRemove.push(checkbox.value);
		}
		
	},
	onNotificationsCancelClick:function(){this.clearSection(true);},	
	
	onPhoneManufacturerChange:function(event){
		var el=Event.element(event);
		
		// Keep track of the model dropdown		
		this.currentPhoneElement=el.next(0);
		
		// Clear out any existing options and add a dummy one
		// alerting the user that we're loading models now...
		this.currentPhoneElement.options.length=0;
		this.currentPhoneElement.options.add(new Option('Loading models...','0'));
		
		if(el.value!=''){
			this.ajaxCall='getmodels';
			this.options.parameters = {i_manufacturerid:el.value}
			new Ajax.Request('/ajax.aspx?x=8Ue8ejq%2f%2fEo%3d',this.options);
		}
	},
	
	onSectionClick:function(event){
		var el=Event.element(event);
		var type=el.readAttribute('type');
		this.currentPane=type;
		if($('p_'+type).className=='form-section-header-on'){
			this.clearSection(true);
		}else{
			this.showSection();
		}
	},

	showSection:function(){
		$$('div.form-section-header-on').each(function(div){
			div.className='form-section-header';
			div.next().hide();
		});
		
		$('p_'+this.currentPane).className='form-section-header-on';
		$('p_'+this.currentPane).next().show();
		$('p_'+this.currentPane).scrollTo();
		
		if(this.currentPane=='notifications'){
			// check to make sure we have not loaded them already
			if($('p_notifications_list').childElements().length==0){		
				this.loadProfileNotifications();
			}
		}
	},
	showSaveSuccess:function(){
		$('p_'+this.currentPane+'_success').show();
	},
	showSaveError:function(message){
		$('p_'+this.currentPane+'_error').show();
		$('p_'+this.currentPane+'_error').update(message);
		$('p_'+this.currentPane).scrollTo();
	},
	clearSection:function(hideall){
		if(hideall){
			$$('div.form-section-header-on').each(function(div){
				div.className='form-section-header';
				div.next().hide();
			});	
		}
		$('p_'+this.currentPane+'_success').hide();
		$('p_'+this.currentPane+'_error').hide();
		$('p_'+this.currentPane+'_error').update('&nbsp;');
	},
	isValidEmail:function(email){
		var GoodChars = "@_-.:/ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		var UpperEmail = email.toUpperCase()
		var ValidChars = true;
		
		for (tfCharNum = 0; tfCharNum > email.length; tfCharNum++) {
			Char = UpperEmail.charAt(tfCharNum);
			for (gcCharNum = 0;  gcCharNum < GoodChars.length;  gcCharNum++) {if (Char == GoodChars.charAt(gcCharNum)){break;}}						
			if (gcCharNum == GoodChars.length){ValidChars = false;break;}
		}		
		if (!ValidChars || email.length < 7 || email.indexOf("@") == "-1" || email.indexOf(".") == "-1" || email.indexOf("@") != email.lastIndexOf("@")) {return (false);}
		return true;	
	},
	limitCharacters:function(event, which, max){
		var el=Event.element(event);
		if(el.value.length>max){
			el.value=el.value.substring(0,max-1);
		}		
		$('p_'+which+'_count').update(el.value.length + ' of <b>' + max + '</b>');
	},
	
	onSuccess:function(r){
        this.options.parameters = {};        
        if(this.ajaxCall=='loadprofile'){
			var profile=r.responseText.evalJSON(true);
			$('p_gendertypeid').value=profile.gendertypeid;
			$('p_genderdisplaytypeid').checked=(profile.genderdisplaytypeid==1)?true:false;
			$('p_birthdatemonth').value=profile.birthdatemonth;
			$('p_birthdateday').value=profile.birthdateday;
			$('p_birthdateyear').value=profile.birthdateyear;
			$('p_birthdatedisplaytypeid').value=profile.birthdatedisplaytypeid;
			$('p_hometown').value=profile.hometown.gsub('&rsquo;','\'');
			$('p_aboutme').value=profile.aboutme.gsub('<br/>','\n').gsub('&rsquo;','\'');
			$('p_signature').value=profile.signature.gsub('<br/>','\n').gsub('&rsquo;','\'');
			$('p_firstname').value=profile.firstname.gsub('&rsquo;','\'');
			$('p_lastname').value=profile.lastname.gsub('&rsquo;','\'');
			$('p_namedisplaytypeid').value=profile.namedisplaytypeid;
			$('p_email').value=profile.email;
			$('p_website').value=profile.website;
			$('p_twitter').value=profile.twitterusername;
			$('p_username').value=profile.username;
			$('p_img').src=profile.img;
			
			// Configure phone sms nofication section
			$('p_phonesmsconfirmed').hide();
			$('p_phonesmsdisabled').hide();
			$('p_phonesmscarrierid').options.length=0;
			$('p_phonesms').value=profile.phonesms;
			$('p_phonesmscode').value=profile.phonesmscode;
			if(profile.phonesmsconfirmed=='true'){
				$('p_phonesmsconfirmed').show();
				$('p_sendsmsverfication').disabled=true;
				$('p_setupsms').disabled=true;
			}else{
				$('p_phonesmsdisabled').show();
				$('p_sendsmsverfication').disabled=false;
				$('p_setupsms').disabled=false;
			}
			$('p_phonesmscarrierid').options.add(new Option('Select your carrier',''));
			for(var x=0; x<profile.phonesmscarriers.length; x++){$('p_phonesmscarrierid').options.add(new Option(profile.phonesmscarriers[x].name,profile.phonesmscarriers[x].id));}
			$('p_phonesmscarrierid').value=profile.phonesmscarrierid;
			
			
			// Set the current counts for the about and signature
			$('p_aboutme_count').update(profile.aboutme.length + ' of <b>2000</b>');
			$('p_signature_count').update(profile.signature.length + ' of <b>150</b>');
			
			// Re-set the manufacturer model dropdowns to it's original state
			// since we may come back here after saving or removing a phone
			for(var x=1; x<6; x++){
				$('p_phone'+x+'_manufacturer').options.length=0;
				$('p_phone'+x+'_model').options.length=0;
				$('p_phone'+x+'_manufacturer').options.add(new Option('Select a manufacturer',''));
				$('p_phone'+x+'_manufacturer').disabled=false;
				$('p_phone'+x+'_model').disabled=false;
				$('p_phone'+x+'_delete').hide();
			}
			
			// Build manufacturers lists
			for(var m=0;m<profile.manufacturers.length;m++){for(var x=1; x<6; x++){$('p_phone'+x+'_manufacturer').options.add(new Option(profile.manufacturers[m].name,profile.manufacturers[m].id));}}					
			
			// Select the manufacturere and add the model
			// of any existing phones that this user has on the account			
			if(profile.phones.length>0){
				var counter=1;
				for(var x=0; x<profile.phones.length; x++){
					// select manufacturer and set current model
					$('p_phone'+counter+'_manufacturer').value=profile.phones[x].manufacturerid;
					$('p_phone'+counter+'_model').options.add(new Option(profile.phones[x].itemname,profile.phones[x].itemid));
					
					// disable so that existing ones can't be changed
					$('p_phone'+counter+'_manufacturer').disabled=true;
					$('p_phone'+counter+'_model').disabled=true;
					
					// Show the delete link and write the phone id
					// to the link as an attribute that we can pick up on delete
					$('p_phone'+counter+'_delete').show();
					$('p_phone'+counter+'_delete').writeAttribute('itemid',profile.phones[x].itemid);
					counter++;
				}
			}
			
			// Show the currently selected section/pane
			this.showSection();
		}else if(this.ajaxCall=='loadprofilenotifications'){
			var data=r.responseText.evalJSON(true);
			var notificationslist=$('p_notifications_list');
			
			for(var n=0; n<data.notifications.length; n++){
				var iscustom=data.notifications[n].iscustom;
				var hasnotification=(data.notifications[n].contactid==0)?false:true;
				
				// add notification only if we either have a contact or it's not custom
				if((iscustom&&hasnotification)||!iscustom){
					var notificationWrapper=new Element('div',{'class':'notification clearfix'});
					var notificationCheckbox=new Element('input',{'type':'checkbox',value:data.notifications[n].notificationid});
					var notificationInfo=new Element('div').update('<b>' + data.notifications[n].name + '</b><br/>' + data.notifications[n].description);
					notificationCheckbox.checked=hasnotification;
					notificationCheckbox.defaultChecked=hasnotification;
					notificationCheckbox.observe('click',this.onNotificationCheck.bindAsEventListener(this));
					notificationWrapper.appendChild(notificationCheckbox);
					notificationWrapper.appendChild(notificationInfo);
					notificationslist.appendChild(notificationWrapper);					
				}
			}		
        }else if(this.ajaxCall=='savebasics'){
			this.showSaveSuccess();			
        }else if(this.ajaxCall=='savepersonal'){
			this.showSaveSuccess();
			this.loadProfile();
        }else if(this.ajaxCall=='savecontact'){
			this.showSaveSuccess();
        }else if(this.ajaxCall=='savelogin'){
			this.showSaveSuccess();
		}else if(this.ajaxCall=='savenotifications'){
			this.showSaveSuccess();
		}else if(this.ajaxCall=='deleteitem'){
			this.showSaveSuccess();
			this.loadProfile();
        }else if(this.ajaxCall=='getmodels'){
			var mods=r.responseText.evalJSON(true);			
			this.currentPhoneElement.options.length=0;
			this.currentPhoneElement.options.add(new Option('Select a model','0'));
			for(var m=0;m<mods.models.length;m++){this.currentPhoneElement.options.add(new Option(mods.models[m].name,mods.models[m].id));}			
        }else if(this.ajaxCall=='sendsmsverification'){
			$('p_sms_success').update('Verification code sent to your phone');
			$('p_sms_success').show();
			$('p_phonesmsconfirmed').hide();
			$('p_phonesmsdisabled').show();
        }else if(this.ajaxCall=='setupsms'){
			$('p_sms_success').update('Mobile notification setup completed!');
			$('p_sms_success').show();
			$('p_phonesmsconfirmed').show();
			$('p_phonesmsdisabled').hide();			
        }
	},
	
	onFailure:function(r){
		this.options.parameters = {};		
		this.showSaveError(r.responseText);
	}	
});


