var dialogueOpen = false;

$(function() {

    // Close all insurance options, underwriting extra Qs, and postcode lookup result
    $('.hideable').each(function() {
        if (
            ($(this).prevAll('.tickboxdiv:first').hasClass('showSection'))
            ||
            ($(this).hasClass('showSection'))
        ){
            // We don't want to hide this on first load
        } else {
            $(this).hide();
        }
    });

    // Reset ticks in checkboxes, as page refreshes in browser can remember them
    $('.tickboxdiv > input:checkbox').each(function() {
        if ($(this).parent().hasClass('showSection')) {
            $(this).attr('checked', true);
        } else {
            $(this).attr('checked', false);
        }
    });

    // Add odd/even class to alternating divs of class "question_outer"
    $('div.question_outer:odd').addClass('odd');
    $('div.question_outer:even').addClass('even');

    // Add odd/even class to divs of class "question_outer_extended", copied
    //   from preceding div of class "question_outer"
    $('div.question_outer_extended').each(function() {
        if ($(this).prevAll('.question_outer:first').hasClass('odd')) {
            $(this).addClass('odd');
        } else {
            $(this).addClass('even');
        }
    });

    // Add slideToggle event for hideable things to checkboxes
    $('.tickboxdiv > input:checkbox').click(function() {
    	if ($(this).attr('checked')) {
            $(this).parent().next('.hideable').slideDown('slow');
    	} else {
    		$(this).parent().next('.hideable').slideUp('slow');
    	}
    });

    // Add slideDown and slideUp event to radio buttons that are tagged (with
    //   .showHideEvent class) to trigger a show/hide event
    $('.showHideEvent > .input_outer > input:radio').click(function() {
        if ($(this).val() == 'Yes') {
            $(this).parent().parent().nextAll('.hideable:first').slideDown('slow');
        } else {
            $(this).parent().parent().nextAll('.hideable:first').slideUp('slow');
        }
    });

    // Add asterisk to all labels with .required class and remove class
    $('label.required').append('*').removeClass('required');

  // Add tooltip events
  $('.small_i').hover(function() {
    $(this).find('img').attr('src', '/images/small_i_over.jpg').end().find('img').css({ 'cursor':'pointer' });
  }, function() {
	$(this).find('img').attr('src', '/images/small_i.jpg');
  });
  $('.small_i').each(function(e) {
	$this = $(this);
    $.data(this, 'title', $this.attr('title'));
	$this.removeAttr('title')				  
  });
  $('.small_i').click(function(e) {
	var top = e.pageY - 4;
	var left = this.offsetLeft + 20;
	if (!($(this).hasClass('activeTooltip'))) {
	  $(this).after('<div id="tooltip"><p>' + $.data(this, 'title') + '</p></div>');
	  $(this).addClass('activeTooltip');
	  var tooltipHeight = $(this).next('#tooltip').outerHeight();
	  var top = top  -(tooltipHeight / 2);
	  $(this).parent().find('#tooltip').css({ top:top, left:left });
	}
    $('.activeTooltip').hover(function() {
      // nothing							 
    }, function() {
      $(this).parent().find('#tooltip').fadeOut(function() {
	  	$(this).remove();
	  });
	  $(this).removeClass('activeTooltip');
    });
  });

    // Set up modal dialogue defaults
    $('body').prepend('<div id="dialog" title=""></div>');

  // set modal defaults
  $.fn.createDialog.defaults = {
        progress: false,
        center: true,
        opacity: 0.7,
        bg: '#000000',
		index: 200
	}
	// modal event for information popups
    $(".modalOpen").each(function() { 
		var current = $(this);
		var optionID = current.attr('id');
		current.hover(function() { $(this).css({"cursor":"pointer"}); });
		current.click(function() { return false; });
		current.createDialog({
			addr: "/landlords/insurance-info/?pageid=" + optionID + '&ajaxHtml=1'
   		});
	});
	/*
	// modal event for letting agent check
	$(".checkAgent").each(function() { 
		$(this).click(function() { return false; });
		$(this).createDialog({
			addr: "/landlords/insurance-agent/?ajaxHtml=1"
   		});
	});
	*/

    // modal event for letting agent check
    $('.checkAgent').each(function() { 
        $(this).click(function() {
            $('#dialog').load('/landlords/insurance-agent/?ajaxHtml=1');
	        $('#dialog').dialog({
	        	'autoOpen': true,
	        	'modal': true,
	        	'resizable': false,
	        	'width': 720,
	        	'title': 'Letting Agent',
	        	'open': function(event, ui) {
	        		$('.ui-widget-overlay').css('opacity', '0.0').animate({'opacity': '0.7'}, 500);
	        		dialogueOpen = true;
	        	},
	        	'beforeclose': function(event, ui) {
	        		if (dialogueOpen) {
                        $('.ui-widget-overlay').animate({'opacity': '0.0'}, 500);
                        setTimeout(closeDialogue, 500);
                        dialogueOpen = false;
                        return false;
	        		}
                }
	        });
	        $('#dialog').dialog('open');
	        return false;
        });
    });

});

function closeDialogue() {
    $('#dialog').dialog({
        'beforeclose': function(event, ui) { return true; }
    });
    $('#dialog').dialog('close');
}

// Simple AJAX post for "modal" forms
// - expects a chunk of HTML to be returned and replaces original modal contents with it
// - outerElementId is usually the form ID, and formId is an optional arg if this is not the case
function ajaxFormPostHtml(outerElementId, url, formId) {
	var formContents;
	var style = $('#' + outerElementId).attr('style'); // Style from dialog boxes retained
	if (typeof(formId) == 'undefined') {
		formContents = $('#' + outerElementId).serialize();
	} else {
		formContents = $('#' + formId).serialize();
	}
	$.post(url, formContents, function(returnHtml) {
		$('#' + outerElementId).replaceWith(returnHtml);
		$('#' + outerElementId).attr('style', style); // Reapply style
	}, 'html');
}

// Complex AJAX post for full forms
// - expects a chunk of XML to be returned that includes new values for output areas (such as quote boxes) and errors
// - returned XML can include special instructions like add/remove fields and redirect to a new URL
function ajaxFormPostXml(formId, url) {
    $.post(url, $('#' + formId).serialize(), handleXmlResponse(returnXml), 'xml');
}

// Complex AJAX post for full forms
// - expects a chucnk of JSON to be returned that includes new values for output areas (such as quote boxes) and errors
// - returned JSON can include special instructions like add/remove fields and redirect to a new URL
// - JSON is cleaned up using (minified copy) of http://www.JSON.org/json2.js
var ajaxJsonTimer;
function ajaxFormPostJson(formId, url) {
	clearTimeout(ajaxJsonTimer);
    ajaxJsonTimer = setTimeout('ajaxError(\'Server not responding after 60 seconds\')', 60000);
    $('#ajaxIndicator').fadeIn('slow');
    $.post(url, $('#' + formId).serialize(), function(returnJson) {
        // We got a response, clear timeout
        clearTimeout(ajaxJsonTimer);
        $('#ajaxIndicator').fadeOut('fast');
        // Parse JSON and send to handler
        try {
            var parsed = JSON.parse(returnJson);
            ajaxErrorClear();
            handleJsonResponse(parsed);
        } catch(err) {
            ajaxError('Server returned bad response: ' + err);
        }
    }, 'text');
}

function ajaxError(msg) {
	var fullMsg = 'Error: ' + msg + ' - please press the submit button at the bottom of the form';
    alert(fullMsg);
    $('#ajaxIndicator').fadeOut('fast');
    var html = '<h1 id="ajaxError" class="errors">' + fullMsg + '</h1>';
    if ($('#ajaxError').length) {
        if ($('#ajaxError').is(':visible')) {
            $('#ajaxError').replaceWith(html);
        } else {
            $('#ajaxError').replaceWith(html);
            $('#ajaxError').hide();
            $('#ajaxError').slideDown();
        }
    } else {
        $('body').prepend(html);
        $('#ajaxError').hide();
        $('#ajaxError').slideDown();
    }
}

function ajaxErrorClear() {
    $('#ajaxError').slideUp('normal', function() { $(this).remove(); });
}

function handleXmlResponse(xml) {
    // Handle redirects
    var redirect = $('redirect').text();
    if (redirect != '') {
        window.location = redirect;
    } else {

	    // Handle errors
	    $('error').each( function() {
	    });

	    // Handle outputs
	    $('output').each( function() {
	    });

    }
}

//var c = 0;

function handleJsonResponse(j) {
	// Display data - these go into spans or divs
	for(var key in j.displaydata) {
		var val = j.displaydata[key];
        $('#' + key).html(val);
	}
	// Instructions - such as hide/show an element, insert/remove an element, redirect to new page
	for(var key in j.instructions) {
		var val = j.instructions[key];
		switch(key) {
            case 'show':
                for (subkey in val) {
                	var subval = val[subkey];
                	$('#' + subval).slideDown();
                }
                break;
            case 'hide':
                for (subkey in val) {
                    var subval = val[subkey];
                    $('#' + subval).slideUp();
                }
                break;
            case 'insert':
                for (subkey in val) {
                    var subval = val[subkey];
                    switch (subval.method) {
                        case 'append':
                            if ($('#' + subval.newId).length) {
                            	if ($('#' + subval.newId).is(':visible')) {
                                    $('#' + subval.newId).replaceWith(subval.html);
                            	} else {
	                                $('#' + subval.newId).replaceWith(subval.html);
	                                $('#' + subval.newId).hide();
	                                $('#' + subval.newId).slideDown();
                            	}
                            } else {
                                $('#' + subval.id).append(subval.html);
                                $('#' + subval.newId).hide();
                                $('#' + subval.newId).slideDown();
                            }
                            break;
                        case 'prepend':
                            if ($('#' + subval.newId).length) {
                                if ($('#' + subval.newId).is(':visible')) {
                                    $('#' + subval.newId).replaceWith(subval.html);
                                } else {
                                    $('#' + subval.newId).replaceWith(subval.html);
                                    $('#' + subval.newId).hide();
                                    $('#' + subval.newId).slideDown();
                                }
                            } else {
                                $('#' + subval.id).prepend(subval.html);
                                $('#' + subval.newId).hide();
                                $('#' + subval.newId).slideDown();
                            }
                            break;
                        case 'after':
                            if ($('#' + subval.newId).length) {
                                if ($('#' + subval.newId).is(':visible')) {
                                    $('#' + subval.newId).replaceWith(subval.html);
                                } else {
                                    $('#' + subval.newId).replaceWith(subval.html);
                                    $('#' + subval.newId).hide();
                                    $('#' + subval.newId).slideDown();
                                }
                            } else {
                                $('#' + subval.id).after(subval.html);
                                $('#' + subval.newId).hide();
                                $('#' + subval.newId).slideDown();
                            }
                            break;
                        case 'before':
                            if ($('#' + subval.newId).length) {
                                if ($('#' + subval.newId).is(':visible')) {
                                    $('#' + subval.newId).replaceWith(subval.html);
                                } else {
                                    $('#' + subval.newId).replaceWith(subval.html);
                                    $('#' + subval.newId).hide();
                                    $('#' + subval.newId).slideDown();
                                }
                            } else {
                                $('#' + subval.id).before(subval.html);
                                $('#' + subval.newId).hide();
                                $('#' + subval.newId).slideDown();
                            }
                            break;
                        case 'replaceWith':
                            if ($('#' + subval.id).is(':visible')) {
                                $('#' + subval.id).replaceWith(subval.html);
                            } else {
                                $('#' + subval.id).replaceWith(subval.html);
                                $('#' + subval.id).hide();
                                $('#' + subval.id).slideDown();
                            }
                            break;
                    }
                    if (subval.callback) {
                    	this[subval.callback]();
                    }
                }
                break;
            case 'remove':
                for (subkey in val) {
                    var subval = val[subkey];
                    $('#' + subval).slideUp('normal', function() { $(this).remove(); });
                }
                break;
            case 'disable':
                for (subkey in val) {
                    var subval = val[subkey];
                    $('#' + subval).attr('disabled', 'disabled');
                }
                break;
            case 'enable':
                for (subkey in val) {
                    var subval = val[subkey];
                    $('#' + subval).removeAttr('disabled');
                }
                break;
            case 'check':
                for (subkey in val) {
                    var subval = val[subkey];
                    $('#' + subval).attr('checked', 'checked');
                }
                break;
            case 'uncheck':
                for (subkey in val) {
                    var subval = val[subkey];
                    $('#' + subval).removeAttr('checked');
                }
                break;
            case 'redirect':
                window.location = val;
                break;
		}
	}
    // Values - these go into inputs of various kinds +
    // Errors - these go into ul's with class "errors"
    for (var key in j.values) {
        var val = j.values[key];
        var err = (j.errors[key]) ? j.errors[key] : '';

        // Are there errors to show for this input?
        if (err != '') {
            // Yes, there are errors
            // Is there data in this field?  (Suppress error otherwise, A.W-J. requested)
            if ($('#' + key).val() != '') {
	            // Does an error ul exist?
	            if ($('#' + key).nextAll('ul.errors').length) {
	                // Yes, update it and show it
	                $('#' + key).nextAll('ul.errors').html('<li>' + err + '</li>').slideDown();
	            } else {
	                // No, create it, hide it, show it
	                $('#' + key).after('<ul class="errors"><li>' + err + '</li></ul>');
	                $('#' + key).nextAll('ul.errors').hide().slideDown();
	            }
            }
        } else {
            // No there are no errors
            // Does an error ul exist?
            if ($('#' + key).nextAll('ul.errors').length) {
                // Yes, hide it
                $('#' + key).nextAll('ul.errors').slideUp();
            }
        }
    }

    //$('#footer').html('<pre>' + dump(j.errors) + '</pre>' + c++);
}



/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
 /*
function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;
    
    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";
    
    if(typeof(arr) == 'object') { //Array/Hashes/Objects 
        for(var item in arr) {
            var value = arr[item];
            
            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' =>\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}
*/
