jQuery(document).ready(function() {
    $('#watch_video').fancybox({
        padding: 10,
        width: 640,
        height: 360,
        autoDimensions: false,
        overlayColor: '#000',
        overlayOpacity: .7,
        transitionIn: 'fade',
        transitionOut: 'fade',
        speedIn: 600,
        speedOut: 600
    });
	
	$('#watch_sizzle').fancybox({
        padding: 10,
        width: 640,
        height: 360,
        autoDimensions: false,
        overlayColor: '#000',
        overlayOpacity: .7,
        transitionIn: 'fade',
        transitionOut: 'fade',
        speedIn: 600,
        speedOut: 600
    });

});

var page = {

	navigation : {
		load : function() {
			if ($('a.logout').length > 0) {
				$('a.logout').click( function() {
					page.display.page('logout', 'Logging Out...');
				});
			}
			if ($('#add-category-link').length > 0) {
				$('#add-category-link').click( function() {
					page.display.modal('category-add');
				});
			}
			if ($('#view-repository-link').length > 0) {
				$('#view-repository-link').click( function() {
					page.display.page('repository', 'Fetching Your Repository...');
				});
			}
			if ($('#manage-users-link').length > 0) {
				$('#manage-users-link').click( function() {
					page.display.page('admin', 'Fetching the Admin Page...')
				});
			}
			if ($('#manage-groups-link').length > 0) {
				$('#manage-groups-link').click(function() {
					page.display.page('groups', 'Fetching the Groups Page...');
				});
			}
             $('#watch_video').fancybox({
                 padding: 10,
                 width: 640,
                 height: 360,
                 autoDimensions: false,
                 overlayColor: '#000',
                 overlayOpacity: .7,
                 transitionIn: 'fade',
                 transitionOut: 'fade',
                 speedIn: 600,
                 speedOut: 600
             });
			 $('#watch_sizzle').fancybox({
                 padding: 10,
                 width: 640,
                 height: 360,
                 autoDimensions: false,
                 overlayColor: '#000',
                 overlayOpacity: .7,
                 transitionIn: 'fade',
                 transitionOut: 'fade',
                 speedIn: 600,
                 speedOut: 600
             });
		}
	},

	login : {
		load : function() {
			$('#login-form').submit( function() {
				page.loading('Logging in...');
			}).ajaxForm( function(data) {
				if (data.indexOf('ERROR::') > 0) {
					page.display.error(data.replace('$ERROR::', ''));
				} else {
					$('#header').load('index.php #header');
                    page.set.contents(data);

				}
			});
		}
	},

	logout : {
		load : function() {
			$('#header').load('index.php #header');
		}
	},

	repository : {
		load : function() {
			$('.category-create').click( function() {
				page.display.modal('category-create', {
					user : $('#user-id').val(),
					group : $(this).parent().parent().parent().parent().attr('class').replace('Group_', ''),
					action : 'create'
				});
			});
			$('.category-update').click( function() {
				page.display.modal('category-update', {
					user : $('#user-id').val(),
					group : $(this).parent().parent().parent().attr('class').replace('Group_', ''),
					action : 'update'
				});
			});
			$('.category-delete').click( function() {
				page.display.modal('delete', {
					type : 'category',
					value : $(this).parent().parent().siblings('.category-name').html(),
					user : $('#user-id').val(),
					group : $(this).parent().parent().parent().attr('class').replace('Group_', ''),
					action : 'delete'
				});
			});
			$('.file-create').click( function() {
				page.display.modal('file-create', {
					user : $('#user-id').val(),
					group : $(this).parent().parent().parent().attr('class').replace('Group_', ''),
					action : 'create'
				});
			});
			$('.file-update').click( function() {
				page.display.modal('file-update', {
					file : $(this).parent().parent().parent().parent().attr('class').replace('File_', ''),
					action : 'update'
				});
			});
			$('.file-delete').click( function() {
				page.display.modal('delete', {
					type: 'file',
					value: $(this).parent().siblings().children('.file-download').attr('title'),
					user : $('#user-id').val(),
					group : $(this).parent().parent().parent().parent().parent().parent().parent().attr('class').replace('Group_', ''),
					file : $(this).parent().parent().parent().parent().attr('class').replace('File_', ''),
					action: 'delete'
				});
			});
		}
	},

	admin : {
		load : function() {
			$('.view-repository').click( function() {
				page.display.modal('repository', {
					user : $(this).parent().parent().parent().parent().attr('id')
				});
			});
			$('.user-create').click( function() {
				page.display.modal('user-create');
			});
			$('.user-update').click( function() {
				page.display.modal('user-update', {
					user : $(this).parent().parent().parent().parent().attr('id'),
					action : 'update'
				});
			});
			$('.user-delete').click( function() {
				page.display.modal('delete', {
					type : 'user',
					value : $(this).parent().parent().parent().siblings('.username').html(),
					user : $(this).parent().parent().parent().parent().attr('id'),
					action : 'delete'
				});
			});
			$('.sort').click( function() {
				var direction;
				if ($(this).hasClass('desc')) {
					direction = 'asc';
					$(this).removeClass('desc').addClass('asc');
				} else {
					direction = 'desc';
					$(this).removeClass('asc').addClass('desc');
				}
				$.ajax({
					url: 'index.php',
					data: {
						action: 'admin',
						column: $(this).attr('rel'),
						direction: direction
					},
					success: function(data) {
						$('#contents').empty().html($(data).children('#contents').html());
					}
				});
			});
		}
	},

	user : {
		create : {
			load : function() {
				$('input[name=params]').val(JSON.stringify({ action: "create" }));
				$('input[type=submit]').click(function() {
					form.errors.clear();
					form.validate.empty($('#username, #password, #email, #group'));
					form.validate.email($('#email'));
					return form.isValid;
				});
				$('form').ajaxForm(function(data) {
					page.loading('Adding New User...');
					if (data.indexOf('ERROR::') > 0) {
						page.display.error(data.replace('$ERROR::', ''));
					} else {
						page.set.contents(data);
					}
				});
			}
		},
		update : {
			load : function() {
				$('input[name=params]').val(JSON.stringify({ action: "update" }));
				$('input[type=submit]').click(function() {
					form.errors.clear();
					form.validate.empty($('#username, #password, #email, #group'));
					form.validate.email($('#email'));
					return form.isValid;
				});
				$('form').ajaxForm(function(data) {
					page.loading('Updating User...');
					if (data.indexOf('ERROR::') > 0) {
						page.display.error(data.replace('$ERROR::', ''));
					} else {
						page.set.contents(data);
					}
				});
			}
		}
	},

	file : {
		update : {
			load : function() {
				$('input[type=submit]').click(function() {
					form.errors.clear();
					form.validate.empty($('#title'));
					return form.isValid;
				});
				$('form').ajaxForm(function(data) {
					page.loading('Updating File...');
					if (data.indexOf('ERROR::') > 0) {
						page.display.error(data.replace('$ERROR::', ''));
					} else {
						page.set.contents(data);
					}
				});
			}
		},
		create : {
			load : function() {
				$('input[type=submit]').click(function() {
					form.errors.clear();
					form.validate.empty($('#title, #file'));
					return form.isValid;
				});
				$('form').ajaxForm(function(data) {
					page.loading('Adding File...');
					if (data.indexOf('ERROR::') > 0) {
						page.display.error(data.replace('$ERROR::', ''));
					} else {
						page.set.contents(data);
					}
				});
			}
		}
	},

	category : {
		update : {
			load : function() {
				$('input[type=submit]').click(function() {
					form.errors.clear();
					form.validate.empty($('#name'));
					return form.isValid;
				});
				$('form').ajaxForm(function(data) {
					page.loading('Updating Category...');
					if (data.indexOf('ERROR::') > 0) {
						page.display.error(data.replace('$ERROR::', ''));
					} else {
						page.set.contents(data);
					}
				});
			}
		},
		create : {
			load : function() {
				$('input[type=submit]').click(function() {
					form.errors.clear();
					form.validate.empty($('#name'));
					return form.isValid;
				});
				$('form').ajaxForm(function(data) {
					page.loading('Adding Category...');
					if (data.indexOf('ERROR::') > 0) {
						page.display.error(data.replace('$ERROR::', ''));
					} else {
						page.set.contents(data);
					}
				});
			}
		}
	},

	group : {
		load : function() {
			$('.group-create').click(function() {
				page.display.modal('group-create', {
					action : 'create'
				});
			});
			$('.group-update').click(function() {
				page.display.modal('group-update', {
					group : $(this).parent().parent().parent().parent().attr('id'),
					action : 'update'
				});
			});
			$('.group-delete').click(function() {
				page.display.modal('delete', {
					type : 'group',
					value : $(this).parent().parent().parent().siblings('.name').html(),
					group : $(this).parent().parent().parent().parent().attr('id'),
					action : 'delete'
				});
			});
		},
		create : {
			load : function() {
				$('input[type=submit]').click(function(){
					form.errors.clear()
					form.validate.empty($('#name'));
					return form.isValid;
				});
				$('form').ajaxForm(function(data) {
					page.loading('Adding Group...');
					if (data.indexOf('ERROR::') > 0) {
						page.display.error(data.replace('$ERROR::', ''));
					} else {
						page.set.contents(data);
					}
				});
			}
		},
		update : {
			load : function() {
				$('input[type=submit]').click(function() {
					form.errors.clear();
					form.validate.empty($('#name'));
					return form.isValid;
				});
				$('form').ajaxForm(function(data) {
					page.loading('Updating Group...');
					if (data.indexOf('ERROR::') > 0) {
						page.display.error(data.replace('$ERROR::', ''));
					} else {
						page.set.contents(data);
					}
				});
			}
		}
	},

	confirm : {
		load : function() {
			$('.cancel').click(function() {
				$('#modal').fadeOut(75);
			});
			$('form').ajaxForm(function(data) {
				page.loading('Deleting...');
				if (data.indexOf('ERROR::') > 0) {
					page.display.error(data.replace('$ERROR::', ''));
				} else {
					page.set.contents(data);
				}
			});
		}
	},

	display : {

		/*
		 * page.display.center()
		 * this function will resize and center the modal the the middle of the page
		 */
		center : function() {
			if ($('#modal').css('display') != 'none') {
				var screenHeight = new Number($(window).height() / 2);
				var modalSplit = new Number($('#modal_top').height() / 2);
				var scrollHeight = new Number($(window).scrollTop());
				var marginTop = new Number((screenHeight - modalSplit) + scrollHeight);
				$('#modal').css('bottom', '-' + $(window).scrollTop() + 'px');
				$('#modal_top').css('margin-top', marginTop + 'px');
			}
		},

		/*
		 * page.display.modal() @description This method will display the modal
		 * popup and populate with the passed action @param string action The name
		 * of the action you are running @param array params Pass in all extra
		 * parameters here as an array
		 */
		modal : function(action, params) {
			$('#modal_content').removeClass('loading').addClass('hide').children('div').empty();
			$('#modal').show();
			$.post('index.php', {
				xmlhttprequest :true,
				action : action,
			  params : JSON.stringify(params)
			}, function(data) {
				if (params) {
					data = data.replace('%%TYPE%%', params.type);
					data = data.replace('%%VALUE%%', params.value);
				}
				page.set.modal(data);
				page.display.center();
				if(params) {
					if ($('input[name=action]').length > 0) {
						$('input[name=action]').val(params.type);
					}
					if (($('input[name=params]').length > 0) && (params)) {
						$('input[name=params]').val(JSON.stringify(params));
					}
				}
			});
			return false;
		},

		error : function(error) {
			$('#modal_content').removeClass('loading').addClass('hide').children('div').empty();
			$('#modal').show();
			page.set.modal($('<p>').html(error).addClass('error'));
			page.display.center();
		},

		/*
		 * page.display.page() @description This method will show the loading menu
		 * while fetching the page template for the passed action @param string
		 * action The name of the action you are running @param array params Pass in
		 * all extra parameters here as an array
		 */
		page : function(action, status, params) {
			page.loading(status);
			$.post('index.php', {
				xmlhttprequest :true,
				action :action,
				params :params
			}, function(data) {
				page.set.contents(data);
				page.display.center();
			});
			return false;
		}

	},

	set : {

		/*
		 * page.set.contents(contents) @description This function will set the
		 * container's html to whatever html is in the contents variable. @param
		 * string contents
		 */
		contents : function(contents) {
			$('#contents').fadeOut(25, function() {
				$(this).html(contents);
				$('#contents').fadeIn(300, function() {
					if($('input[name=modal]').length > 0) {
						var action = $('input[name=modal-action]').val();
						var params = JSON.parse($('params').html());
						page.display.modal(action, params);
					} else {
						$('#modal').fadeOut(75, function() {
							page.load();
						});
					}
				});
			});
		},

		/*
		 * page.set.modal(contents) @description This function will set the modal
		 * popup's html to whatever html is in the contents variable. @param string
		 * contents
		 */
		modal : function(contents) {
			$('#modal_content div').html(contents).parent().removeClass('hide');
		}

	},

	/*
	 * page.loading(loadingText) @description This is a method to simply pass text
	 * to a function that will display loading information for ajax requests prior
	 * to completing and sending callback data. @param string loadingText
	 */
	loading : function(loadingText) {
		$('#modal_content').addClass('loading').children('div').html('<p>' + loadingText + '</p>');
		$('#modal').show();
	},

	/*
	 * page.load() @description This event runs every time a page is successfully
	 * loaded
	 */
	load : function() {

		// modal behavior
		$('#modal').css('display: none');
		$('.modal_close').click(function() {
			$('#modal').fadeOut(100);
		});

		// retrieve the navigation bar
		$.post('index.php', {
			xmlhttprequest : true,
			action : 'navigation'
		}, function(data) {
			$('#navigation').html(data).show();
			page.navigation.load();
		});

		// set the window move event to keep modal centered
		$(window).resize(function() {
			page.display.center();
		}).scroll(function() {
			page.display.center();
		});

	}

}

var form = {
	isValid: true,
	errors: {
		add: function(field, text) {
			form.isValid = false;
			$('label[for='+field+']').addClass('error').attr('title', text.replace('%%field%%', $('label[for='+field+']').html().replace('*', ''))).focus();
		},
		remove: function(field) {
			$('label[for='+field+']').removeClass('error');
		},
		clear: function() {
			$('label').removeClass('error');
			form.isValid = true;
		}
	},
	validate: {
		empty: function(fields) {
			$(fields).each(function() {
				if ($.trim($(this).val()).length == 0) {
					form.errors.add($(this).attr('id'), '%%field%% cannot be blank.');
				} else {
					form.errors.remove($(this).attr('id'));
				}
			});
		},
		zipcode: function(fields) {
			$(fields).each(function() {
				var pattern = /^\d{5}$|^\d{5}-\d{4}$/;
				if ($.trim($(this).val()).length > 0) {
					if (!$(this).val().match(pattern)) {
						form.errors.add($(this).attr('id'), 'Please provide a valid US Zip Code.')
					} else {
						form.errors.remove($(this).attr('id'));
					}
				}
			});
		},
		phone: function(fields) {
			$(fields).each(function() {
				var pattern = /^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/;
				if ($.trim($(this).val()).length > 0) {
					if (!$(this).val().match(pattern)) {
						form.errors.add($(this).attr('id'), 'Please provide a valid phone number.');
					} else {
						form.errors.remove($(this).attr('id'));
					}
				}
			});
		},
		email: function(fields) {
			$(fields).each(function() {
				var pattern = "";
//				var pattern = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
				if ($.trim($(this).val()).length > 0) {
					if (!$(this).val().match(pattern)) {
						form.errors.add($(this).attr('id'), 'Please provide a valid e-mail address.');
					} else {
						form.errors.remove($(this).attr('id'));
					}
				}
			});
		},
		compare: function(fields, comparisons) {
			$(fields).each(function(i) {
				if ($.trim($(this).val()).length > 0) {
					if ($(this).val() != $(comparisons[i]).val()) {
						form.errors.add($(this).attr('id'), 'Your e-mail addresses do not match.');
						form.errors.add($(comparisons[i]).attr('id'), 'Your e-mail addresses do not match.');
					} else {
						form.errors.remove($(this).attr('id'));
						form.errors.remove($(comparisons[i]).attr('id'));
					}
				}
			});
		},
		checked: function(group) {
			if ($(group).filter(':checked').length == 0) {
				$(group).each(function() {
					form.errors.add($(this).attr('id'), 'You must select an option.');
				});
			} else {
				$(group).each(function() {
					form.errors.remove($(this).attr('id'));
				});
			}
		}
	}
};
