$(document).ready(function() {
	
	$("#requestList").tablesorter({widgets: ['zebra']});

	$('#withdraw').dialog({
	bgiframe: true,
	autoOpen: false,
	modal: true,
	resizable: false,
	draggable: false,
	width: 520,
	height: 340
	});
	
	$('#accept').dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		resizable: false,
		draggable: false,
		width: 520,
		height: 340
	});
	
	$('#discussion').dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		resizable: false,
		draggable: false,
		width: 520,
		height: 340
	});
	
	$('#discussionRequest').dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		resizable: false,
		draggable: false,
		width: 520,
		height: 340
	});
	
	$('#loginform').dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		resizable: false,
		draggable: false,
		width: 520,
		height: 340,
		title: 'Log in'
	});

	$('#equote').accordion({
		autoHeight: false,
		navigation: true
	});
	
	$('#new_request').button();

    jQuery.validator.addMethod("greaterThan", function(value, element, params) {
    	if ($('input:radio[name="form_type"]:checked').val() != 'Service') {
    		return true;
    	};
        if (!/Invalid|NaN/.test(new Date(value))) {
            return new Date(value) > new Date($(params).val());
        }
        return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val())); 
    },'Must be greater than expiry date.');
    
    jQuery.validator.addMethod("notEqual", function(value, element, param) {
    	  return this.optional(element) || value != param;
    	}, "Please select a county");
	
	$('#request_form').validate({
		rules: {
			title: {required: true},
			details: {required: true},
			keyphrases1: {required: true},
			expires: {required: true},
			deadline_alt: {greaterThan: '#expires'}
		}
	});
	
	$('#expires_alt').datepicker({defaultDate: +14, changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', altField: '#expires', altFormat: 'yy-mm-dd'});
	$('#deadline').datepicker({changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', altField: '#deadline_alt', altFormat: 'yy-mm-dd'});
	$('#deadline').hide();
	$('label[for="deadline"]').hide();
	$('#quantity').show();
	$('label[for="quantity"]').show();
	$('#ProductType').click(function() {
		$('#deadline').hide();
		$('label[for="deadline"]').hide();
		$('#quantity').show();
		$('label[for="quantity"]').show();
	});
	$('#ServiceType').click(function() {
		$('#quantity').hide();
		$('label[for="quantity"]').hide();
		$('#deadline').show();
		$('label[for="deadline"]').show();
	});
	
	$('#withdrawRequest').button().click(function(){
		$('#withdraw').dialog('open').load("/equote/equote-templates-schools/confirm-withdraw-request-popup.php?reqID=" + $(this).attr('reqID'), function() {
			$('#cancelWithdrawRequest').button().click(function () { $('#withdraw').dialog('close'); });
			$('#confirmWithdrawRequest').button().click(function () {
				$('#withdraw').dialog('close').load('/equote/withdrawRequest.php?request_id=' + + $(this).attr('reqID'), function() { location.reload(); });
			});
		});
	});
	
	$('#withdrawResponse').button().click(function () {
		$('#withdraw').dialog('open').load("/equote/equote-templates-companies/confirm-withdraw-quote-popup.php?respID=" + $(this).attr('respID'), function() {
			$('#cancelWithdrawQuote').button().click(function () { $('#withdraw').dialog('close'); });
			$('#confirmWithdrawQuote').button().click(function () {
				$('#withdraw').dialog('close').load('/equote/withdrawQuote.php?response_id=' + + $(this).attr('respID'), function() { location.reload(); });
			});
		});
	});
	
	$('#acceptResponse').button().click(function () {
		$('#accept').dialog('open').load("/equote/equote-templates-schools/confirm-accept-quote-popup.php?respID=" + $(this).attr('respID'), function() {
			$('#cancelAcceptQuote').button().click(function () { $('#accept').dialog('close'); });
			$('#confirmAcceptQuote').button().click(function () {
				$('#accept').dialog('open').load('/equote/acceptQuote.php?response_id=' + + $(this).attr('respID'), function() {  location.reload(); });
			});
		});
	});
	
	$('#sendMessagetoQuote').button().click(function(){
		$('#discussion').dialog('open').load('/equote/addDiscussionQuote.php', {
			response_id: $(this).attr('respID'),
			text: $('#discussionText').val(),
			who: $(this).attr('who')}, function() {
			location.reload();
		});
	});
	
	function createAccount()
	{
		$('#loginform').load('/equote/createAccount.php', bindButtons);
		$('#requestcreateaccount').validate();
		return false;
	}
	
	function createAccountSubmit()
	{
		$('#requestcreateaccount').validate({
			rules: {
				schoolname: {required: true},
				county: {required: true, notEqual: 'Please select...'},
				email: {required: true, email: true},
				email_confirm: {required: true, email: true, equalTo: '#email'},
				password_first: {required: true},
				password_confirm: {required: true, equalTo: '#password_first'},
				terms: {required: true}
			},
			onsubmit: false
		});
		if ($('#requestcreateaccount').valid())
		{
			$('#loginform').load('/equote/createAccount.php', {schoolname: $('#schoolname').val(), county: $('#county').val(), email: $('#email').val(), password: $('#password_first').val(), action: 'submit'}, bindButtons);
		}
		return false;
	}
	
	function login()
	{
		$('#loginform').load('/equote/login.php', {username: $('#username').val(), password: $('#password').val()}, bindButtons);
		return false;
	}
	
	function submitRequest()
	{
		$('#request_form').submit();
		$('#loginform').dialog('close');
	}
	
	function bindButtons()
	{
		$('#createaccount').button().click(createAccount);
		$('#createaccountsubmit').button().click(createAccountSubmit);
		$('#accountcreatedsubmit').button().click(submitRequest);
		$('#confirmrequestsubmit').button().click(submitRequest);
		$('#loginbutton').button().click(login);
	}
	
	$('#submitRequest').button().click(function() {
		$('#loginform').dialog('open').load('/equote/login.php', bindButtons);
		return false;
	});
	
	$('#questionForm').hide();
	
	$('#QuestionType').click(function() {
		$('#quoteForm').hide();
		$('#questionForm').show();
	});
	
	$('#response_form').validate();
	
	$('#QuoteType').click(function() {
		$('#quoteForm').show();
		$('#questionForm').hide();
	});
	
	$('#submit_quote_question').button().click(function() {
		$('#response_form_question').submit();
		return false;
	});
	
	$('#submit_quote').button().click(function() {
		$('#response_form').submit();
		return false;
	});
	
	$('.view_responses').button().click(function() {
		$('.quickform').dialog('open').load('/equote/viewResponses.php?request_id=' + $(this).attr('reqID'));
	});
	
	$('.delete_request').button().click(function() {
		$('.quickform').dialog('open').load('/equote/delete_request.php?request_id=' + $(this).attr('reqID'));
	});
	
	$('#sendMessagetoRequest').button().click(function(){
		$('#discussionRequest').dialog('open').load('/equote/addDiscussionRequest.php', {
			request_id: $(this).attr('requestID'),
			text: $('#discussionTextRequest').val(),
			who: $(this).attr('who')}, function() {
			location.reload();
		});
	});
	
	function convertToQuote()
	{
		$('#convert').button();
	}
	
	$('#convertToQuote').button().click(function() {
		$('#withdraw').dialog('open').load('/equote/convertToQuote.php', {response_id: $(this).attr('respID')}, convertToQuote);
	});
	
	$('#confirm_delete').button();
	
	$('.add_response').button();
	
	$('#keyphrases').autocomplete({
		source: '/get_data_json.php?type=keyword'
	});
	
	$('#keyphrases1').autocomplete({
		source: '/get_data_json.php?type=keyword'
	});
	
	$('#keyphrases2').autocomplete({
		source: '/get_data_json.php?type=keyword'
	});
	
	$('#keyphrases3').autocomplete({
		source: '/get_data_json.php?type=keyword'
	});
	
	$('#keyphrases4').autocomplete({
		source: '/get_data_json.php?type=keyword'
	});
	
	$('#addContactInfo').button().click(function () {
		alert('In order to accept a quote, you must provide us with your full contact details');
		return false;
	});
	
});


