function keepAlive ( ) {
	setInterval('jQuery.get("profile.html");',5*60*1000);
}

function whenEmpty ( filter, msg ) {
	return jQuery(filter)
		.bind('focus', function(){
			if(this.value == msg){
				this.value = '';
//				jQuery(this).removeClass('empty');
			}
		})
		.bind('blur',function(){
			if(this.value == '' || this.value == msg){
				this.value = msg;
//					.addClass('empty');
			}
		})
		.blur();
}

function validateEditProfile ( evt ) {
  
  evt.preventDefault();

	var val = new Validator(this);
	
	// Biography
	var Gid =  document.getElementById('groupid').value;

	if(Gid == 1){
  	val.EditorRequired('Biography');
	}
	
	//General
	val.required('First Name','first_name');
	val.required('Last Name','last_name');
	val.required('E-mail','email');
	val.match('Password','password','repeatpassword');
	
	//Contact
	if(Gid == 1){
	val.required('Address','address1');
	val.required('City','city');
	val.required('Zip','postal_code');
	//val.required('Country','country');
	val.required('Telephone','telephone');
	//val.phone('Telephone','telephone');
	val.filecheck('Photo','mdeda4feu_input_avatar', 'avatar');
	
	
	
	//Affiliations
	
			for(var n=0;n < affiliations.list.length;n++){
				if(affiliations.list[n].node.css('display') != 'none'){
					var pkey = 'affiliation_'+(n+1)+'_';
					var ptitle = 'Affiliation '+(n+1)+': ';
					val.required(ptitle+'Order',pkey+'order');
					val.required(ptitle+'Name',pkey+'name');
					val.required(ptitle+'Type',pkey+'type');
					val.required(ptitle+'City',pkey+'city');
					//val.phone(ptitle+'Telephone',pkey+'telephone');
				}
			}
	}

	if(val.errors.length){
		showErrorDialog('Form Incomplete',val.getErrorMessage());
		return false;
	}
	this.submit();
}

function showErrorDialog ( title, msg ) {
	if(!jQuery("#errorDialog").length){
		jQuery('<div />')
			.attr('id','errorDialog')
			.hide()
			.appendTo(document.body)
			.dialog({
				bgiframe: true,
				modal: true,
				autoOpen: false,
				width: 400
			});
	}
	jQuery('#ui-dialog-title-errorDialog')
		.html(title);
	jQuery('#errorDialog')
		.html(msg)
		.dialog('open');
}

Validator = function ( form ) {
	
	this.form = jQuery(form);
	
	this.errors = [];
	this.getErrorMessage = function ( ) {
		return this.errors.join('<br />');
	};
	this.getNode = function ( key ) {
		return this.form.find('*[name$="input_'+key+'"]');
	};
	this.getValue = function ( key, trim ) {
		var node = this.getNode(key);
		if(node.length)
			return trim ? jQuery.trim(node.val()) : node.val();
		return '';
	};
	this.required = function ( title, key ) {
		if(!this.getValue(key,true).length)
			this.errors.push("<b>"+title+"</b> - Field is required");
	};
	this.match = function ( title, key1, key2 ) {
		if(this.getValue(key1) !== this.getValue(key2))
			this.errors.push("<b>"+title+"</b> - Fields don't match");
	};
	/*this.phone = function ( title, key ) {
		var val = this.getValue(key,true);
		if(!val.length) return; //Skip if empty
		val = val.replace(/[^\d]/g,'');
		(val.length == 10) //Format and set phone number
			? this.getNode(key).val(val.substr(0,3)+'-'+val.substr(3,3)+'-'+val.substr(6,4))
			: this.errors.push("<b>"+title+"</b> - Not a valid phone number: ###-###-####");
	};*/
	this.getNodeId = function ( key ) {
		return this.form.find('*[id$="'+key+'"]');
	};
	this.getValueOfId = function ( key, trim ) {
		var node = this.getNodeId(key);
		if(node.length)
			return trim ? jQuery.trim(node.val()) : node.val();
		return '';
	};
	
	this.EditorRequired = function ( title ) {
			
		editor_id = tinyMCE.selectedInstance.editorId;
		editor_id +='_ifr'
	
		thefield=eval("this.form."+tinyMCE.selectedInstance.formTargetElementId);                
	
		//To get Current Count.///////////////////////////////////////////////////////////////////////////////////////////////////////////
		obj=document.getElementById(editor_id);
		if(obj.contentDocument){
			content=obj.contentDocument.body.innerHTML //FireFox (getContent() messes up cursor position)
		}
		else
		{
			content=top.frames[editor_id].document.body.innerHTML //IE - avoid getContent() due to spellchecker and cursor issues
		}
	
		content = content.replace(/(<([^>]+)>)/ig,"");
		content = content.replace(/&nbsp;/g,"");
		content = content.replace(/<br>/gi, " ")
		content = content.substr(0,content.length-1); //to remove last space
		content = content.replace(/\s+/gi, " ")

		if(content == '')
			this.errors.push("<b>"+title+"</b> - Field is required");
	};
	
	this.filecheck = function ( title, key, name ) {
		
		var val	= 	this.getValueOfId(key,true);
		
		/*if(!this.getValue(name,true).length && val=='') {
			this.errors.push("<b>"+title+"</b> - Field is required");
		}
		else {*/	
				
				var strExtension 	=	document.getElementById('feu_extension').value;
				
				arrExtension		=	strExtension.split(",");
				
				flag=0;
				
				for(var index=0;index<arrExtension.length;index++) {
					if(arrExtension[index].toLowerCase() == (val.substring(val.lastIndexOf('.')).toLowerCase())) {	
						flag=1; 
						break; 
					}
				}
			
				if(flag==0 && val != '') { this.errors.push("<b>"+title+"</b> - Please upload "+strExtension); }
		//}
		
	};
	
};


var affiliations = {
	list: new Array(),
	node: null,
	listNode: null,
	addNode: null,
	register: function ( item ) {
		return this.list.push(item) - 1;
	},
	setAddNode: function ( ) {
		if(!this.addNode){
			//Init
			this.addNode = jQuery('<div />')
				.attr('id','editprofile_affiliations_add')
				.append(jQuery('<a href="#" class="addLink">Add Item</a>')
					.click(this.hitch(this,'onAdd'))
				);
			this.node.append(this.addNode);		
		}
		if(jQuery(this.list).filter(':hidden').length){
			this.addNode.show();
		}else{
			this.addNode.hide();
		}
		return this;
	},
	onAdd: function ( ) {
		jQuery(this.list).filter(':hidden:first').show();
		this.setAddNode();
		return false;
	},
	remove: function ( item ) {
		if(item.idx < this.list.length - 1 && jQuery(this.list[item.idx+1]).css('display') != 'none' ){
			//Not the last item
			return this
				.transfer(item,this.list[item.idx+1])
				.remove(this.list[item.idx+1]);
		}
		jQuery(item).hide();
		return this.setAddNode();
	},
	transfer: function ( item1, item2 ) {
		var inputs2 = jQuery(item2).find("input[type='text'],select");
		jQuery(item1).find("input[type='text'],select").each(function(idx){
			var input1 = jQuery(this);
			var input2 = jQuery(inputs2.get(idx));
			switch(input1.attr('tagName')){
				case 'INPUT':
					var val = input2.val();
					input2.val(input1.val());
					input1.val(val);
					break;
				case 'SELECT':
					var val = input2.attr('selectedIndex');
					input2.attr('selectedIndex',input1.attr('selectedIndex'));
					input1.attr('selectedIndex',val);
					break;
			}
		});
		return this;
	},
	hitch: function(/*Object*/thisObject, /*String*/method){
		var args = [];
		for(var x=2; x<arguments.length; x++)
			args.push(arguments[x]);
		var fcn = thisObject[method];
		return function(){
			var ta = args.concat([]);
			for(var x=0; x<arguments.length; x++)
				ta.push(arguments[x]);
			return fcn.apply(thisObject, ta);
		};
	},
	init: function ( nodeId ) {
		this.node = jQuery("#"+nodeId);
		this.listNode = this.node.children('ul');
		this.listNode.children('li').each(affiliation);
		this.setAddNode();
	}
};
affiliation = function ( idx, node ) {
	this.node = jQuery(node);
	this.idx = null;
	
	this.onRemove = function ( evt ) {
		//Reset it
		jQuery(this).find("input[type='text']").val('');
		jQuery(this).find('select').attr('selectedIndex',0);
		//Hide it
		affiliations.remove(this);
		return false;
	};
	this.init = function ( ) {
		//Register it
		this.idx = affiliations.register(this);

		// Hide if unused
		if(!this.node.find("input[class$='_name']").val()){
			this.node.hide();
		}
		
		// Add Remove
		this.node.append(jQuery('<div />')
			.attr('id','editprofile_affiliations_remove')
			.append(jQuery('<a href="#">Remove</a>')
				.click(affiliations.hitch(this,'onRemove'))
			)
		);
	};
	this.init();
};


jQuery(document).ready(function(){
	//Make tabs
	jQuery('.tabs').tabs();
	
	//Login Box
	jQuery('#login_input_username input,#login_input_password input')
		.bind('focus',function(){
			jQuery(this.parentNode).removeClass('empty');
		})
		.bind('blur',function(){
			if(this.value == ''){
				jQuery(this.parentNode).addClass('empty');
			}
		})
		.blur();
	
	//Search Box
	whenEmpty('#search_input input','enter keyword, recipe or chef name');

	//Recent Chefs
	/*jQuery(".carousel").carousel({
		pagination: true,
		prevBtnInsert: "appendTo",
		nextBtnInsert: "appendTo",
		nextBtn: '<div class="next"></div>',
		prevBtn: '<div class="prev"></div>'
	});
	*/

	//Fix for the edit profile page
	jQuery('#contentLeft input[type=password]').val('');
	//Setup Affiliations
	affiliations.init('editprofile_affiliations');
	whenEmpty('#editprofile input[class*="_start"],#editprofile input[class*="_end"]','MM-YYYY');
	
	//Edit Profile Validation
	jQuery('#editprofile form').submit(validateEditProfile);

	//Create Recipe
	whenEmpty('#cntnt01recipe_prep_time','in minutes');
	whenEmpty('#cntnt01recipe_cook_time','in minutes');

	//My Recipes Sort
	jQuery('#my_recipe_sort li a').each(function(){
		var num = (this.title == 'all')
			? jQuery('#recipe_list li').length
			: jQuery('#recipe_list li div.'+this.title).length;
		if(num){
			this.innerHTML += ' ('+num+')';
		}
	})
	.click(function(){
		jQuery('#my_recipe_sort li').removeClass('active');
		if(this.title == 'all'){
			jQuery(this).parent('li').addClass('active');
			jQuery('#recipe_list li').show();
		}else{
			jQuery(this).parent('li').addClass('active');
			jQuery('#recipe_list li')
				.hide()
				.find('div.'+this.title)
				.parent('li')
				.show();
		}
		return false;
	});
	
	//Tell a Friend
//	jQuery('#tell_a_friend').dialog({
//		bgiframe: true,
//		modal: true,
//		autoOpen: false,
//		width: 420
//	});
//	jQuery('a[href$="#tell"]').click(function(){
//		jQuery('#tell_a_friend').dialog('open');
//		return false;
//	});
});
