// Loads up the various functions we are going to use

jQuery(function() {
	jQuery(".popuptrigger a, a.popuptrigger, input.popuptrigger").live('click', function() {    // creates an empty popup when
		clickFire(this);
		return false;
	});
	jQuery(".edspopupclose").live('click', closePop); //attaches event to popup close
	//jQuery("#edspopupbkg2,#edspopupbkg").live('click', closePop); //attaches event to popup close
	jQuery(".helpDetail .helpBox, #homeGuide li").click(function() {
		rtn = true;
		jQuery(this).find('h2 a, a.videoLink').each(function() {
			clickFire(this, null, 'popupVid');
			rtn = false;
		});
		return rtn;
	});
	jQuery('.refreshPage').live('click', function() {
		window.location.reload();
		return false;
	});
});

//takes a popup box (as a jQuery object) and positions it on the screen (hopefully the middle)
function positionPopup(box, speed) {
	if (speed == null) speed = 0;
	iWidth = box.find('.edspopupinner > *:last').outerWidth() +7 //7 is for the margin on the left
	iHeight = box.find('.edspopupinner > *:last').outerHeight() +15 // avoid a small scrollbar;
	//set maximum height for popup box
	iHeight = Math.min(iHeight, jQuery(window).height()-170);
    //offset due to scrolling: jQuery(window).scrollTop()
    //height of popup box: jQuery('edspopupbox').height()
    //height of viewable screen: jQuery(window).height()
    var iTop = Math.max(Math.round(jQuery(window).scrollTop() + ((jQuery(window).height() / 2) - ((iHeight+50) / 2))), jQuery(window).scrollTop() + 25);
    var iLeft = Math.max(Math.round(jQuery(window).scrollLeft() + ((jQuery(window).width() / 2) - ((iWidth+50) / 2))), jQuery(window).scrollLeft() + 10);
    //position the box
    //set width of outer box to match inner box + padding
    box.animate({ top: iTop + 'px', left: iLeft + 'px', width: iWidth+50 + 'px' }, speed);
    box.css({margin: '0 auto', position:'absolute', overflow:'visible'});
    box.find('.edspopupinner').animate({ width: iWidth + 'px', height: iHeight + 'px' }, speed);
    //and position the background
    jQuery('#edspopupbkg').css({ height: jQuery(document).height() + 'px' });
}


var popupPanicTimeout;
// this is what we do when an ajax enabled link / button is clicked.
// by default will load the href if fired from a  link, or post a form if called form an input element.
// e is an optional url to call instead.
// cb is a callback function to fire on successful loading of content
function clickFire(e, cb, c) {
	//what to do if complete doesn't get called quick enough!
	popupPanicTimeout = setTimeout(function() {
		jQuery('.edspopupinner').html('<div><h2>Don\'t panic!</h2><p>This page seems to be taking a long time to load. You may want to <a href="#" class="refreshPage">try refreshing it manually</a>.</p></div>');
		//alert('no complete!');
		complete(true);
	}, 8000);
	//actions to perform when complete
	var complete = function(fast) {
		//phew, all good this time
		clearTimeout(popupPanicTimeout);
		var title_text = jQuery('.edspopupinner h1').remove().text();
		jQuery('#edspopupbox .title').text(title_text).append('<em>' + title_text + '</em>');
		//focus on the first form element found.
		jQuery('.edspopupinner').find('input[type=text]:first').focus();
		//reposition popup box for new size
		positionPopup(jQuery('#edspopupbox'), fast ? 0 : 700);
		//make the button nice
		nicebuttons();
		//bind form validation rules
		if (typeof bindValidationRules == 'function') bindValidationRules('.edspopupinner');
		//and any other callback
		if (typeof cb == 'function') cb(jQuery('.edspopupinner'));
	};
    //show the popup box
    if (jQuery('#edspopupbox').length == 0) {
        jQuery("body").append('<div id="edspopupbkg"></div><div id="edspopupbkg2"></div><div id="edspopupbox"><div class="cornerTR"><div class="title"></div><div class="cornerBR"><div class="cornerBL"><a href="" class="edspopupclose"><span>Close</span></a><div class="edspopupinner"></div></div></div></div></div>');
    }
    if (c != null) jQuery('#edspopupbox .edspopupinner').addClass(c);
   //check if we are dealing with a link or a form
    var addr = '';
    var aType = 'GET';
    var fData = null;
    var div = '';
    //if it's a string, it's a GET
    if (typeof e == 'string') {
    	addr = e;
    }
    // it's a link, so we do a GET
    else if (jQuery(e).is('a')) {
    	addr = (e.href.replace(/.*\/\/[^\/]+/, '')); // replace everything before the first /
    }
    // it's a button, so we do a POST
    else if (jQuery(e).is('input')) {
    	var f = jQuery(e).parents('form');
    	addr = f.attr('action');
    	aType = 'POST';
    	// serialize the form, remembering to add the input element we clicked to the data.
    	fData = f.serialize() + '&' + jQuery(e).attr('name') + '=' + jQuery(e).val();
    }
    //if we get sent a jQuery object, just do it.
    else if (typeof e == 'object') {
    	//positionPopup(jQuery('#edspopupbox'));
    	jQuery('.edspopupinner').append(e);
    	complete(true);
    	return false;
    }
    else {
    	addr = null;
    }
    //hide warning messages, show a loader
    jQuery('.edspopupinner .co_message').remove();
    //show a loading animation
    if (jQuery('.edspopupinner .loadingAnim').length == 0) {
    	jQuery('.edspopupinner').prepend('<p class="loadingAnim"></p>');
    }
    positionPopup(jQuery('#edspopupbox'));
    jQuery('#edspopupbox .loadingAnim').css({ width: jQuery('#edspopupbox .edspopupinner').innerWidth() - 10, height: jQuery('#edspopupbox .edspopupinner').innerHeight() - 10 }).show();
    // time to fire off the ajax
    if (addr != null) {
    	//check for a specified id to select (and remove # anchors from url)
    	if (addr.indexOf('#') > 0) {
    		div = addr.substring(addr.indexOf('#'));
    		addr = addr.substring(0, addr.indexOf('#'));
    	}
    	//add request=partial so that headers and footers are ignored
		addr += (addr.indexOf('?') == -1 ? '?' : '&') + 'request=partial'
    	jQuery.ajax({
    		type: aType,
    		url: addr,
    		data: fData,
    		dataType: 'html',
    		success: function(data, status) {
    			try {
    				var jData = jQuery(data);
    			}
    			catch (e) { }
    			if (jData == undefined) {
    				location.href = addr.replace('request=partial', '');
    				return;
    			}
    			jQuery('.edspopupinner *:not(.loadingAnim)').remove();
    			jQuery('.edspopupinner .loadingAnim').fadeOut();
    			//we check for #popupwrapper to ensure no redirection to non-popup page has occurred.
    			//all popup-safe redirects must persist the request=partial qs flag to strip header and footer.
    			if (jData != undefined && jData.length > 0 && jData.filter('#popupwrapper').length > 0) {
    				//check if our div is one of the root elements (filter), or one of the children (find)
    				if (div.length > 0 && (jData.filter(div).length > 0 || jData.find(div).length > 0)) {
    					if (jData.filter(div).length > 0) {
    						jQuery('.edspopupinner').append(jData.filter(div));
    					}
    					else {
    						jQuery('.edspopupinner').append(jData.find(div));
    					}
    				}
    				else {
    					jQuery('.edspopupinner').append(jData.html());
    				}
    				complete();
    			}
    			else {
    				closePop();
    				location.href = addr.replace('request=partial', '');
    			}
    		},
    		error: function() {
    			closePop();
    			location.href = addr.replace('request=partial', '');
    		},
    		timeout: 7000,
    		cache: false
    	});
    }
    return false;
}

//function to fire from flash performing a javascript:function()
//crucially, this function is wrapper for clickFire, that does not return a value!
function hrefFire(url) {
    clickFire(url);
}

// hides the popupbox, and the backgrounds etc.
function closePop() {
	clearTimeout(popupPanicTimeout);
    jQuery("#edspopupbkg").remove();
    jQuery("#edspopupbkg2").remove();
    jQuery("#edspopupbox").remove();
    return false;
}
