$(document).ready(function(){
	//Input Text Placeholders
	$(':text, :password, textarea').each(setDefault);
	$(':text, textarea').focus(clearDefault);
	$(':text, :password, textarea').blur(setDefault);
	
	//if pharmacy locator
	$('.login form').hide();
	
	$('.login .btn-login').click(function(){
		$('.login form').show();
		$('#join-now').hide();
		$(this).hide();
	});
	
	$('#search-box').submit(function(){
		$(this).find(':text').each(clearDefault);
	});
	$('.login form').submit(function(){		
		if ($('#bcp-username').val() == '' || $('#bcp-username').val() == $('#bcp-username').attr('title') || $('#bcp-password').val() == '') {
			return false;
		}
	});
	$('#dashboard-login').submit(validateDashboardLogin);
	
	//Form toggle details
	$('.form .details').hide();
	$('.form .show:checked').parent().next().show();

	$('.form .show').click(function(){
		$(this).parent().next().toggle();
	});	
	
	$('#featureselect .radio input').change(function(){
		$('#preview img').attr('src','/img/patient/feature/style-'+$(this).val()+'.png');
	});
	if ($('input.date').length){		
		$('.date').datepicker({
			dateFormat:($('.db-format').length ? 'yy-mm-dd':'mm/dd/yy')
		});
		//$('.date').datepicker('option', 'dateFormat', 'yy-mm-dd');
	}
	//login colorbox			
	$('.jobLink').each(levelCheck);		
		
	
	//Form validations
	$('#contactform').submit(submitContact);
	$('#NodeAdminEditForm').submit(submitEdit);
	$('#NodeAdminAddForm').submit(submitAdd);
	$('#insurance-form').submit(submitInsurance);
	$('#news-form').submit(submitNews);
	$('#tablet-form').submit(submitTablet);
	$('#update-form').submit(submitUpdate);
	
	//Combo check-box stuff
	$('.combo-checkbox :text').focus(function(){
		$(this).prevAll(':checkbox, :radio').attr('checked', true);
	});
	$('.combo-checkbox :text').each(function(){
		if ($(this).val() != ''){
			$(this).prevAll(':checkbox, :radio').attr('checked', true);
		}		
	});
	//add more history
	$('#expand-changes').click(expandHistory);
	
	//changing the parent
	$('#NodeParentId').change(function(){
        var url = "";
        url = "/nodes/getchildren/" + $("#NodeParentId option:selected").val();
        $.getJSON(url,
            function(data){  
        			var str = "<option value=''>At the end</option>";
	        		if (!data.error) {	
	        			$.each(data, function(i,item){
	        				str += "<option value='"+i+"'>";
	        				str += item;
	        				str += "</option>";
	                    });
        			}
	        		else {
	        			$('#NodePlace').html(str);
	        		}
	        		$('#NodePlace').html(str);
        	});
    }).change();
	
	//sortable stuff
	if ($('#sidenav').hasClass('sortable')){
		$('#sidenav').sortable({
			items:'li.nodeItem',
			cursor:'move',
			update:function(e, ui){				
				var order = [];				
				$.each($('li.nodeItem'), function(pos, item){
					order.push({id:item.id.replace('node_','')});				
				});
				var out = $.param({item:order});
				sortPages($(this).attr('title'), out);
			}
		});
		//deal with IE
		$('ul.nested-nav').bind('mousedown', function(e) {
			  e.stopPropagation();
		});

		$('.nested-nav').sortable({
			items:'li.subNodeItem',
			cursor:'move',
			update:function(e, ui){				
				var order = [];
				
				$.each($('li.subNodeItem'), function(pos, item){
					order.push({id:item.id.replace('node_','')});				
				});
				var out = $.param({item:order});				
				sortPages($(this).attr('title'), out);
			}
		});
	}
	if ($('#tree-view').hasClass('sortable')){
		$('#tree-view').sortable({
			items:'> li',
			cursor:'move',
			update:function(e, ui){				
				var order = [];
				
				$.each($('#tree-view > li'), function(pos, item){
					order.push({id:item.id.replace('tree-node','')});				
				});
				var out = $.param({item:order});
				var parentid = $(this).attr('id').replace('tree-node','');
				sortPages(parentid, out);
			}
		});
		//deal with IE
		$('ul.nested-nav').bind('mousedown', function(e) {
			  e.stopPropagation();
		});
		$('#tree-view .nested-nav').sortable({
			items:'> li',
			cursor:'move',
			update:function(e, ui){
				var parent = $(ui.item).parent();
				
				var order = [];
				
				$.each($(parent).find('li'), function(pos, item){
					order.push({id:item.id.replace('tree-node','')});				
				});
				var out = $.param({item:order});
				var parentid = $(parent).parent().attr('id').replace('tree-node','');
				sortPages(parentid, out);
			}
		});
	}
	function sortPages(parentid, out){
		$.ajax({
			url: "/nodes/sort/"+parentid,
			type: "POST",
			data: out,
			dataType:'text',
			success: function(feedback){}
		});
	}
	//tree view
	if ($('#tree-view').length){
		$('#tree-view').treeview({
			animated:'fastest',
			collapsed:true
		});
		$('#tree-control .expand').click(function(e){			
			$('.expandable-hitarea').each(function(e){
				if (!$(this).hasClass('closed-hitarea')){
					$(this).click();
				}
			});
			return false;
		});
		$('#tree-control .collapse').click(function(e){			
			$('.collapsable-hitarea').each(function(e){
				$(this).click();				
			});
			return false;
		});
		//VERSION VIEW COLORBOX
		$('#tree-view .versions').each(function(){
			$(this).find('a.preview').colorbox({ 
				opacity: 0.8, 
				width:'1000px', 
				height:'592px', 
				rel:$(this).attr('id'), 
				/*iframe:true,*/ 
				current:'Version {current} of {total}'
			});
		});
		$('body').delegate('#revert-version, .versions .revert', 'click', function(){return confirm('Do you want to revert to this version?');});
	}
	//adding file stuff
	$('#add-attachment-file').each(checkExistingFile);
	$('#add-attachment-file, #new-document-level').change(checkExistingFile);
	$('#add-attachment-form').submit(addAttachmentCheck);
});


//Set Default Text
function setDefault(){		
	if ($(this).attr('type') == 'password'){
		var placeholder = '#'+$(this).attr('id')+'_placeholder';		
		if (!$(placeholder).length){			
			$(this).after('<input type="text" id="'+$(this).attr('id')+'_placeholder" value="'+$(this).attr('title')+'" class="default-text" />');
			$(placeholder).focus(function(){
				$(this).hide();
				$('#'+$(this).attr('id').replace('_placeholder','')).show();
			});
		}
		if ($(this).val() == ''){
			$(this).hide();
			$(placeholder).show();
		}else{
			$(placeholder).hide();
		}
	}else if ($(this).val() == '' || $(this).val() == $(this).attr('title')){
		$(this).val($(this).attr('title'));
		$(this).addClass('default-text');
	}
}
//Clears Default Text
function clearDefault(){	
	if ($(this).attr('id').indexOf('_placeholder') != -1){
		var password = '#'+$(this).attr('id').replace('_placeholder', '');	
		$(this).hide();
		
		$(password).show().focus();
	}else{ 
		$(this).removeClass('default-text');
		if ($(this).val() == $(this).attr('title')){
			if ($(this).attr('id') == 'bcp-username' || $(this).attr('id') == 'dashboard-username'){
				$(this).val('bcp');
				var obj = $(this)[0];
			    if(obj.createTextRange) { //IE only
			        /* Create a TextRange, set the internal pointer to
			           a specified position and show the cursor at this
			           position
			        */ 
			        var range = obj.createTextRange(); 
			        range.move("character", 3); 
			        range.select(); 
			    }

			}else{
				$(this).val('');
			}
		}
	}
}
//generic validate functions
function validateInputs(validators){
	var message = '';
	var fail;
	for (var n=0; n<validators.length; n++){
		if (validators[n].type == 'email'){
			fail = !validateEmail($(validators[n].id).val()) && $(validators[n].id).val() != '';									
		}else if (validators[n].type == 'checked'){
			fail = $(validators[n].id+' :checked').length == 0;			
		}else{
			fail = $(validators[n].id).length && ($.trim($(validators[n].id).val()) == '' || $(validators[n].id).val() == $(validators[n].id).attr('title'));
		}
		if (fail){
			message += validators[n].message+'\n';
		}
	}
	if (message == ''){	
		for (var n=0; n<validators.length; n++){
			if ($(validators[n].id).is(':text, textarea') &&  $(validators[n].id).val() == $(validators[n].id).attr('title')){
				$(validators[n].id).val('');
			}
		}
		return true;
	}else{
		alert(message);
		return false;
	}
}
//validates an email using unicode characters
function validateEmail(email){
	var emailreg = /^((([a-zA-Z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-zA-Z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/; 
	if (!emailreg.exec(email))
		return false;
	else
		return true;
}
//validates and readies a contact form for submission
function submitContact(){
	var validate = [
        {id:'#MessageName', message:'Please enter your name'},
        {id:'#MessageEmail', message:'Please enter your email'},
        {id:'#MessageEmail', message:'Please enter a valid email', type:'email'},
        {id:'#MessageTitle', message:'Please enter a subject'},
        {id:'#MessageBody', message:'Please write something'}
	];
	return validateInputs(validate);
}
//validates and an edit form for submission
function submitEdit(){
	var validate = [
        {id:'.log-description', message:'Please provide a summary of changes!'},
        {id:'#CurrentContentTitle', message:'You must provide a title!'},
        {id:'#CurrentContentSlug', message:'You must provide a path name!'}
	];
	return validateInputs(validate);	
}
//validates and an add form for submission
function submitAdd(){
	var validate = [
        {id:'#ContentTitle', message:'You must provide a title!'},
        {id:'#ContentSlug', message:'You must provide a path name!'}
	];
	return validateInputs(validate);	
}
//validates and an add form for submission
function submitInsurance(){
	var validate = [
	    {id:'.two-col', message:'Please check at least one item', type:'checked'},
        {id:'.email', message:'You must provide an email!'},
        {id:'.email', message:'You must provide a valid email!', type:'email'}
	];
	return validateInputs(validate);	
}
//validates adding/editing news
function submitNews(){
	var validate = [
	    {id:'#NewsTitle', message:'Please provide a title for this article!'},
        {id:'#NewsDate', message:'Please provide a date for this article!'}
	];
	return validateInputs(validate);
}
//validates adding/editing tablets
function submitTablet(){
	var validate = [
	    {id:'#TabletTitle', message:'Please provide a title for this issue!'},
        {id:'#TabletDate', message:'Please provide a date for this issue!'}
	];
	return validateInputs(validate);
}
//validates adding/editing updates
function submitUpdate(){
	var validate = [
	    {id:'#UpdateTitle', message:'Please provide a title for this update!'}        
	];
	return validateInputs(validate);
}
function expandHistory(){
	
	$.ajax({
		url:'/version/more_history',
		type:'POST',
		dataType:'json',
		error:function(req,status,error){
			alert(status+': '+error);
		},
		success:function(data){
			if (!$('#history-area').hasClass('expanded')){
				$('#history-area').addClass('expanded');
				for(var n=0; n<data.logs.length; n++){
					var log = data.logs[n];
					var row = $('<tr></tr>');
					if (n%2 == 1){
						$(row).addClass('alt-row');
					}
					var link = $('<a></a>');				
					$(link).html(log.title);
					$(link).attr('href',log.path);
					var level;
					if (log.visibility == 0){
						level = 'blue';
					}else if (log.visibility == 1){
						level = 'green';
					}else{
						level = 'pink';
					}
					$(link).addClass(level);
					
					var linkcell = $('<td></td>');
					$(linkcell).append($(link));
					
					var namecell = $('<td></td>');
					$(namecell).html(log.name);
					
					var changedcell = $('<td></td>');
					$(changedcell).html(log.changed);
					
					var summarycell = $('<td></td>');
					$(summarycell).html(log.summary);
					$(row).append($(linkcell)).append($(namecell)).append($(changedcell)).append($(summarycell));
					$('#changes-table tbody').append($(row));				
				}				
			}
		}
	});
	return false;
}
//checks for existing file in upload
function checkExistingFile(){
	if ($('#add-attachment-file').val() != ''){
		$.ajax({
			url:'/attachments/check',
			data:{file:$('#add-attachment-file').val(),level:$('#new-document-level').val()},
			dataType:'html',
			beforeSend:function(){
				$('#file-message').html('<img src="/img/ajax/loadingAnimation.gif" alt="" /><br />Loading...');
			},
			success:function(data){
				$('#file-message').html(data);
			}
		});
	}else{
		$('#file-message').html('');
	}
}
//checks add attachment
function addAttachmentCheck(){
	if ($('#file-message .not-logged').length){
		alert('You must log in!');
		return false;
	}else{
		if ($('#file-message .warning').length){			
			return confirm('This will overwrite a file. Do you want to?');
		}
	}
}
//when the dashboard login is submitted
function validateDashboardLogin(){	
	$.colorbox.close();
	if ($('#dashboard-username').val() == '' || $('#dashboard-username').val() == $('#dashboard-username').attr('title') || $('#dashboard-password').val() == '') {
		return false;
	}
}
//applies these events to the colorbox login
function readyColorboxLogin(){
	$('#dashboard-login :text, #dashboard-login :password').each(setDefault);
	$('#dashboard-login :text, #dashboard-login :password').focus(clearDefault);
	$('#dashboard-login :text, #dashboard-login :password').blur(setDefault);
	$('#dashboard-login').submit(validateDashboardLogin);
}
//checks the level of the link if login prompt should be opened
function levelCheck(){
	var rolelevel = 0;
	
	if ($(this).hasClass('rolelevel2')){
		rolelevel = 2;
	}else if ($(this).hasClass('rolelevel3')){
		rolelevel = 3;
	}else if ($(this).hasClass('rolelevel4')){
		rolelevel = 4;
	}else if ($(this).hasClass('rolelevel5')){
		rolelevel = 5;
	}
	var content = $(this).html();
	
	
	var loggedlevel = Number($('#member-level').val());
	//$(this).html(content+' '+rolelevel+','+loggedlevel);
	if (loggedlevel + 1 < rolelevel){
		var href = $(this).attr('href');
		if (href.indexOf('/uploads/members/') != -1){
			href = href.replace('/uploads/members','')+'&folder=memberuploads';
		}
		$(this).colorbox({href:"/dashboard/login?redirect="+href, opacity: 0.8, width: 345, height: 95, onComplete:readyColorboxLogin});
	}	
}
