// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

var fixDialogWidth = function(dialog) {
	// reduce overall dialog width by width of the padding
	jQuery(dialog).css('width', jQuery(dialog).width() - (2*parseInt(jQuery(dialog).css('padding-left'))) + 'px');
	jQuery(dialog).css('height', 'auto');
	jQuery(dialog).css('visibility', 'visible');
}

var confirm = function(message, callback, el) {
	jQuery('#confirmContent').html(message);
	jQuery('#confirmDialog')
	.dialog('open')
	.find('a.confirmOk')
	.unbind('click')
	.click(function(){
		callback.apply(el);
		return false;
	});
}

var generateDialogHtml = function(link, mode) {
	var path = link.attr('href');
	var isLarge = link.hasClass('large');
	// Check for bogus "notfirst" attribute, which allows us to avoid
	// creating another dialog if one with the same ID already exists.
	var isFirst = !link.attr('notfirst');
	generateDialogHtmlFromVars(path, isLarge, isFirst, mode);
}

var generateDialogHtmlFromVars = function(path, isLarge, isFirst, mode) {
	var helpKey = mode == 'file' ? path.replace(new RegExp('/',"g"), "_") : path.substring(1);
	var id = isLarge ? 'lgHelpDialog' : 'helpDialog';
	if (isFirst) {
		jQuery('#'+id)
		.clone()
		.attr('id', id+'-'+helpKey)
		.appendTo("body");

		jQuery.ajax({
			url: mode == 'file' ? path : "/help/get/"+helpKey,
			success: function(html){
				jQuery('#'+id+'-'+helpKey+' .helpContent').html(html);
			}
		});
	}
}


var dialogOptions = {
	modal: false,
	height: 'auto',
	width: 400,
	open : function() {
		fixDialogWidth(jQuery(this));
	},
	resize : function() {
		fixDialogWidth(jQuery(this));
	},
	resizeStop : function() {
		fixDialogWidth(jQuery(this));
	},
	resizable: false,
	draggable: false,
	autoOpen: false,
	overlay: {
		opacity: 0.5,
		background: 'black'
	}
};

jQuery(document).ready(function() {

	jQuery('a.submitForm').click(function(){
		var el = jQuery(this);
		// check for nextStep class -- set flag if found
		if (el.hasClass('nextStep')) {
			el.parents('form').append('<input type="hidden" name="data[redirect_next_step]" value="1" />');
		}

		// check for addAnother class -- set flag if found
		if (el.hasClass('addAnother')) {
			el.parents('form').append('<input type="hidden" name="data[add_another]" value="1" />');
		}

		// finds the nearest form ancestor and submits it
		el.parents('form:first').submit();
		return false;
	})





	// HELP DIALOG
	// generate all help dialogs
	jQuery('a.help').each(function(){
		generateDialogHtml(jQuery(this));
	});

	// POPUP DIALOG
	// generate all popup dialogs
	jQuery('a.popup').each(function(){
		generateDialogHtml(jQuery(this), 'file');
	});
	


	jQuery('div[id^=helpDialog]').dialog(dialogOptions);
	jQuery('div[id^=lgHelpDialog]').dialog(jQuery.extend({}, dialogOptions, {
		width:800
	}));
	jQuery("div#signupDialog").dialog(jQuery.extend({}, dialogOptions, {
		width:800,
		close: function() {
			window.location.reload();
		},
		modal: true,
		position: "top"
	}));

	jQuery('a.help, a.popup').click(function(){
		var el = jQuery(this);
		var mode = el.hasClass('popup') ? 'file' : '';
		var path = el.attr('href');
		var helpKey = mode == 'file' ? path.replace(new RegExp('/',"g"), "_") : path.substring(1);
		var id = el.hasClass('large') ? 'lgHelpDialog' : 'helpDialog';
		if (!el.hasClass("large")) {
			var pos = el.offset();
			var scroll = getPageScroll();
			var top = Math.max(pos.top - scroll[1] - 150, 0);
			jQuery('#'+id+'-'+helpKey).dialog("option", "position", [pos.left - scroll[0], top]);
		}
        if (el.attr('title') != ''){
            jQuery('#'+id+'-'+helpKey).dialog("option", "title", el.attr('title'));
        }
		jQuery('#'+id+'-'+helpKey).dialog('open');
		return false;
	});
	 


	// CONFIRM DIALOG
	jQuery('#confirmDialog').dialog(jQuery.extend({}, dialogOptions, {
		modal:true
	}));


	// GLOBAL DIALOG CLOSE LISTENER
	jQuery('a.dialogClose').live("click", function(){
		jQuery(this).parents('div[id*=Dialog]:first').dialog('close');
		return false;
	});

	if (typeof(window.postMessage) != "undefined") {
        jQuery("a.joinNowDialog").click(function() {
			jQuery("div#signupDialog iframe").attr("src", "/mentor/join-now/d:true?r=" + Math.random());
			jQuery("div#signupDialog").dialog("open");
			return false;
		});
		jQuery("a[href*=mentor/join-now]").click(function() {
			jQuery("div#signupDialog iframe").attr("src", "/mentor/join-now/d:true?r=" + Math.random());
			jQuery("div#signupDialog").dialog("open");
			return false;
		});

		jQuery(window).bind("message", function(e){
			var message = e.originalEvent.data.evalJSON();
			if (message.height) {
				jQuery("#signupDialog iframe").height(message.height + "px");
			}
			if (message.title) {
				jQuery('#signupDialog').dialog('option', 'title', message.title);
			}
			if (message.helpLink) {
				generateDialogHtmlFromVars(message.helpLink.path, message.helpLink.isLarge, message.helpLink.isFirst, message.helpLink.mode);
			}
			if (message.initHelp) {
				jQuery('div[id^=lgHelpDialog]').dialog(jQuery.extend({}, dialogOptions, {
					width:700
				}));
			}
			if (message.openHelp) {
				jQuery(message.openHelp).dialog('open');
			}
			if (message.close) {
				jQuery('#signupDialog').dialog("close");
			}
			if (message.scrollToTop) {
                console.log('scrollToTop');
				jQuery('html, body').animate({scrollTop:0}, 'fast');
			}
		}, false);
	}


    jQuery('.networkGroupOption img, .networkGroupOption p').click(function(){
        var e = jQuery('input', jQuery(this).closest('.networkGroupOption'));
        if (e.attr('checked')){
            e.removeAttr('checked');
        } else {
            e.attr('checked', 'checked');
        }
        e.change();

        return false;
    });
    jQuery('.networkGroupOption input').change(function(){
        // this is called after the values have changed
        // clear all, then re-check
        if (jQuery(this).attr('checked')){
            jQuery('.networkGroupOption input').removeAttr('checked');
            jQuery(this).attr('checked', 'checked');
        } else {
            jQuery('.networkGroupOption input').removeAttr('checked');
        }

        jQuery(this).closest('form').submit();
        return false;
    });
});

