//addEvent(window,'load',dialogBoxesWatch);
jQuery(document).ready(function() {
	//jQuery('#moxBoxMedError').hide();
	dialogBoxesWatch();
});

function dialogBoxesWatch(doc) {
	if(doc==null) doc = jQuery(document);
    doc.find('span.editable span.listTitle').click(function() {
		jQuery(this).parent().removeClass('editable').addClass('editing'); return false;
    });
    doc.find('.canceledit').click(function() {
		jQuery(this).parent().parent().removeClass('editing').addClass('editable'); return false;
    });
	doc.find('.closeBoxSml').click(function() {
		jQuery('#dBoxSml').fadeOut("fast", function() {
			jQuery('#mbsContent').html('');
		}); return false;
	});
	doc.find('.closeBoxMed').click(function() {
		jQuery('#dBoxMed').fadeOut("fast", function() {
			jQuery('#dbox-content').html('');
		}); return false;
	});
	doc.find('.mbsFetch').click(function () {
		jQuery('.moxBoxMed').hide();
		jQuery(".moxBoxSml").hide();
		jQuery('#dBoxSml').addClass('loading').show();
		var path = jQuery(this).attr('class').substring(jQuery(this).attr('class').lastIndexOf(' ') + 1, jQuery(this).attr('class').indexOf('-'));
		var id = jQuery(this).attr('class').substring(jQuery(this).attr('class').indexOf('-') + 1);
		jQuery('#mbsContent').load(getAccUrl() + 'partial/' + path + '/' + (id > 0 ? id : ''), function (data, textStatus, obj) {
			jQuery('#dBoxSml').removeClass('loading');
			if (textStatus == 'success') {
				dialogBoxesWatch(jQuery(this));
				jQuery(this).slideDown("fast");
			}
			else if (obj.status == 401) {
				jQuery('#dBoxSml').hide();
				jQuery('#dbox-content').html(data).show();
				jQuery('#dBoxMed').show();
				dialogBoxesWatch(jQuery('#dbox-content'));
			}
			else {
				dboxSmlError(this);
			}
		});
		return false;
	});
	doc.find('.mbmFetch').click(function() {
	    var path = jQuery(this).attr('class').substring(jQuery(this).attr('class').lastIndexOf(' ') + 1, (jQuery(this).attr('class').indexOf('-') > 0 ? jQuery(this).attr('class').indexOf('-') : jQuery(this).attr('class').length));
	    var id = jQuery(this).attr('class').substring(jQuery(this).attr('class').indexOf('-') + 1);
	    if (id.indexOf('-') > 0) id=id.replace('-', '/');
	    doDBoxFetch(path + '/' + (id.match(/(\d+\/?)+/) ? id : ''))
	    return false;
	});
	doc.find('.deleteLnk').click(function() {
		jQuery('.moxBoxMed').hide();
		jQuery(".moxBoxSml").hide();
		var li = jQuery(this).parents('li[class!=delete]').eq(0);
		var title = '\'' + li.find('.listTitle').eq(0).html() + '\'';
		var id = li.attr('class').substring(li.attr('class').indexOf('-')+1);
		if(id.indexOf(' ') >-1) id = id.substring(0,id.indexOf(' '));
		if(li.attr('class').indexOf('template') >-1) {
			jQuery('#updateDetails').val('Delete');
			jQuery('#mbsDeleteForm > .deleteCancel > a').text('Cancel and don\'t delete');
			showDeleteDialog('Are you sure you want to delete '+title+'?','deleteTemplate', 'templateid', id);
		}
		else if (li.attr('class').indexOf('design') > -1) {
		    jQuery('#updateDetails').val('Delete');
		    jQuery('#mbsDeleteForm > .deleteCancel > a').text('Cancel and don\'t delete');
		    showDeleteDialog('Are you sure you want to delete this version?', 'deleteDesign', 'designid', id);
		}
		else if (li.attr('class').indexOf('project') > -1) {
		    jQuery('#updateDetails').val('Delete');
		    jQuery('#mbsDeleteForm > .deleteCancel > a').text('Cancel and don\'t delete');
		    showDeleteDialog('Are you sure you want to delete ' + title + '?', 'deleteProject', 'projectid', id);
		}
		else if (li.attr('class').indexOf('client') > -1) {
			jQuery('#updateDetails').val('Delete');
			jQuery('#mbsDeleteForm > .deleteCancel > a').text('Cancel and don\'t delete');
			showDeleteDialog('Are you sure you want to delete '+title+'?','deleteClient', 'clientid', id);
		}
		else if(li.attr('class').indexOf('permission') >-1) {
			jQuery('#updateDetails').val('Remove');
			jQuery('#mbsDeleteForm > .deleteCancel > a').text('Cancel and don\'t remove');
			showDeleteDialog('Are you sure you want to remove \''+title+'\' from this project?','deletePermission', 'permissionid', id);
		}
		return false;
	});
	doc.find('.delClientLnk').click(function() {
		jQuery('.moxBoxMed').hide();
		jQuery('.moxBoxSml').hide();
		var h2 = jQuery(this).parents('h2').eq(0);
		var title = '\'' + h2.find('.listTitle').eq(0).html() + '\'';
		var id = jQuery(this).attr('class').substring(jQuery(this).attr('class').indexOf('-')+1);
		jQuery('#updateDetails').val('Delete');
		jQuery('#mbsDeleteForm > .deleteCancel > a').text('Cancel and don\'t delete');
		showDeleteDialog('Are you sure you want to delete '+title+'?','deleteClient', 'clientid', id);
		return false;
	});
	doc.find('#signoffConfirm').submit(function() {
		jQuery('#dBoxMed').addClass('loading');
	});
	doc.find('.addFormLink').click(function() {
	    jQuery(this).parents('.addFormContainer:first').children('ul').hide().siblings('form').slideDown("fast");
	    return false;
	});
	doc.find('.closeFormLink').click(function() {
	    jQuery(this).parents('.addFormContainer:first').children('form').slideUp("fast").siblings('ul').show();
	    return false;
	});
    doc.find('#addTemplateForm').submit(function() {
		jQuery('#dBoxMed').addClass('loading');
    });
    doc.find('#betaMsgForm').submit(function() {
        jQuery('#dBoxMed').addClass('loading');
        jQuery('#dbox-content input[name=page]').val(location.href);
        params = jQuery('#dbox-content').find('input,textarea');
        jQuery('#dbox-content').load(getAccUrl() + 'partial/betamsg', params, function(data, textStatus) {
            jQuery('#dBoxMed').removeClass('loading');
            if (textStatus == 'success') dialogBoxesWatch(jQuery(this));
            if (textStatus == 'error') dboxError(this);
        });
        return false;
    });
	doc.find('.clientLoginUserLnk').click(function() {
		editClientLogin(this); return false;
	});
	doc.find('#clientLoginForm #delUserBtn').click(function() {
	    if (confirm('This will permanently delete this client login. Are you sure you wish to continue?'))
            clientLoginSubmit(jQuery('#dbox-content').find('input:hidden,input:text,input:password,input#delUserBtn,:checkbox:checked'));
	    return false;
	});
	doc.find('#clientLoginForm #updateDetails').click(function() {
        clientLoginSubmit(jQuery('#dbox-content').find('input:hidden,input:text,input:password,:checkbox:checked'));
		return false;
	});
	doc.find('.rss a').click(function() {
		var rssurl = jQuery(this).attr('href');
		jQuery('#rssfeedlink').attr('href',rssurl).text('http://' + location.host + rssurl);
		jQuery('.moxBoxMed').hide();
		jQuery('.moxBoxSml').hide();
		jQuery('#dBoxSml').show();
		jQuery('#mbsRssFeed').slideDown('fast');
		return false;
	});
	if (jQuery('#moxBoxMedError').length == 0) { jQuery('#clientLoginFormTitle').hide(); jQuery('#clientLoginForm').hide(); }
	jQuery('#bcProject').change(function() {
	    if (jQuery(this).val() > 0)
	        doDBoxFetch('basecamp/' + jQuery('#bciProjectId').val() + '/' + jQuery(this).val());
        else
            doDBoxFetch('basecamp' + jQuery('#bciProjectId').val());
       });
	var uploadFormElement = jQuery('#addMultipleTemplatesForm');
	if (uploadFormElement.size() > 0) {
		var uploader = new MultipleFileUploader({
			formElement: uploadFormElement,
			uploadQueueElement: jQuery('.upload-queue'),
			enableFlash: true,
			acceptedFileExtensions: '*.jpg;*.jpeg;*.png;*.gif',
			acceptedFilesDescription: 'Images',
			flashUrl: '/flash/swfupload.swf',
			flashUploadUrl: document.location.toString(),
			flashUploadButton: {
				id: 'flash-upload-placeholder',
				width: 119,
				height: 38,
				imageUrl: '/images/layout/browseButton.png?1'
			},
			addHiddenFields: true,
			fileSizeLimit: '6 MB',
			onFlashUploaderLoaded: function () {
				jQuery('.upload-queue-wrapper').show();
				jQuery('.upload-limit-notice').show();
				doc.find('.deleteCancel').before(closeButtonWrapper);
				doc.find('.deleteCancel').hide();
			},
			onFlashStartedUploading: function () {
				closeButtonText.html('Cancel Uploads');
			},
			onFlashEndedUploading: function () {
				closeButtonText.html('Done');
			},
			httpErrorMapper: function (code) {
				if (code == 302 || code == 401) {
					return 'Upload failed because you have been logged out.';
				} else if (code == 403) {
					return 'Upload failed because you have run out of storage space.';
				} else if (code == 415) {
					return 'Upload failed because the image is in an invalid format.';
				} else if (code == 418) {
					return 'Upload failed; make sure the filename is valid and that you have permission to upload.';
				} else {
					return 'Upload failed.';
				}
			},
			customErrorChecker: function (data) {
				if (data.match('Login\</title\>')) {
					return {
						isError: true,
						message: 'Upload failed because you have been logged out.'
					};
				} else {
					return false;
				}
			}
		});

		var closeButtonWrapper = jQuery('<p><a class="MBbutton arrow"><span>Cancel</span></a></p>');
		var closeButtonText = closeButtonWrapper.find('span');
		var closeButton = closeButtonWrapper.find('a');
		closeButton.attr('href', window.location.toString().split('#')[0]);
		closeButton.click(function () {
			uploader.cancelUpload();
		});
	}
}

function doDBoxFetch(path) {
	jQuery('.moxBoxMed').hide();
	jQuery(".moxBoxSml").hide();

	// Set the new position relative to the scrolling top. Additionally, other styles
	// are forcefully overridden because old custom CSS may break things.
	jQuery('.moxBoxMedContainer').
		css('top', jQuery(document).scrollTop() + 100 + 'px').
		css('position', 'absolute').
		css('left', 'auto').
		css('margin', '0');
	jQuery('.moxBoxMed, .moxBoxMedContainer .close').
		css('margin-left', 'auto').
		css('margin-right', 'auto');

	jQuery('#dBoxMed').addClass('loading').show();
	jQuery('#dbox-content').load(getAccUrl() + 'partial/' + path, function(data, textStatus, obj) {
	    jQuery('#dBoxMed').removeClass('loading');
	    if (textStatus == 'success') {
	        dialogBoxesWatch(jQuery(this));
	        jQuery(this).slideDown("fast");
	        if (jQuery(this).find('#signoffComment').length > 0)
	            tinyMCE.execCommand('mceAddControl', false, 'signoffComment');
	    }
	    else if (obj.status == 401) {
	        jQuery(this).html(data);
	        dialogBoxesWatch(jQuery(this));
	        jQuery(this).slideDown("fast");
	    }
	    else if (textStatus == 'error')
	        dboxError(this);
	});
}

function clientLoginSubmit(params) {
    jQuery('#dBoxMed').addClass('loading');
    id = jQuery('#userclientid').val();
    jQuery('#dbox-content').load(getAccUrl() + 'partial/clientlogins/' + id, params, function(data, textStatus) {
        jQuery('#dBoxMed').removeClass('loading');
        if (textStatus == 'success') {
            dialogBoxesWatch(jQuery(this));
            jQuery(this).slideDown("fast");
            if (jQuery('#moxBoxMedError').length == 0) jQuery('.clientlogins-' + id).text('edit client logins');
        }
        if (textStatus == 'error') dboxError(this);
    });
}

function dboxError(obj) {
    jQuery('.moxBoxMed:not(#dbox-error)').hide();
    dialogBoxesWatch(jQuery(obj));
    jQuery('#dbox-error').slideDown("fast");
}

function dboxSmlError(obj) {
    jQuery('.moxBoxSml:not(#dboxsml-error)').hide();
    dialogBoxesWatch(jQuery(obj));
    jQuery('#dboxsml-error').slideDown("fast");
}

function showDeleteDialog(title, action, idn, idv) {
	var div = jQuery('#dBoxSml');
	div.find('h3').eq(0).html(title);
	jQuery('#smlBoxAction').val(action);
	jQuery('#smlBoxId').attr("name",idn);
	jQuery('#smlBoxId').val(idv);
	div.show();
	jQuery('#mbsDeleteForm').slideDown("fast");
}

function editClientLogin(e) {
	var li = jQuery(e).parents('li[class!=delete]').eq(0);
	var cName = li.find('.clientName').eq(0).html();
	var cEmail = li.find('.clientEmail').eq(0).html();
	var cProjects = li.find('.projectAccess').eq(0).text().split(',');
	var id = li.attr('class').substring(li.attr('class').indexOf('-')+1);
	var cActive = (li.find('.userActive').length >0 && id >0) ? false : true;
	//jQuery('#clientLoginForm:visible').hide();
	document.editClientLoginForm.userid.value = id;
	document.editClientLoginForm.username.value = (id==-1) ? '' : cName;
	document.editClientLoginForm.useremail.value = (id==-1) ? '' : cEmail;
	jQuery('.projectAccessChk').each(function() {
	    var id = this.id.substring(this.id.indexOf('-')+1);
	    this.checked = (jQuery.inArray(id, cProjects) >=0);
	});
	document.editClientLoginForm.useractive.checked = cActive;
	document.editClientLoginForm.clientLoginSubmit.value = (id==-1) ? 'Create user login' : 'Edit user login';
	jQuery('#clientLoginFormTitle').text((id==-1) ? 'Create user login' : 'Edit user login').show();
	if (id == -1) { jQuery('#deleteUser').hide() } else { jQuery('#deleteUser').show() }
	jQuery('#clientLoginForm').slideDown("fast");
}
