//these vars are 'placeholders' for data being passed around from popups/wizards.
window.top.wizardData	= null; //this holds data returned by the wizard
window.top.wizard 	   	= null; //this holds the 'instance' of the wizard
window.top.independentbox = null;
window.top.independentData = null;

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}




/**
* This is JQuery to hook in when the document is loaded/ready - this is where we will be defining
* methods and code to run upon load.
*/
$(document).ready(


	function(){

		//configure an error handler for ajax.
		$.ajaxSetup({
			error:function(x,e){
				if(x.status==0){
					var message = 'You are offline!!\n Please Check Your Network.';
				}else if(x.status==404){
					var message = 'Requested URL not found.';
				}else if(x.status==500){
					var message = 'Internal Server Error';
				}else if(e=='parsererror'){
					var message = 'Error.\nParsing JSON Request failed.';
				}else if(e=='timeout'){
					var message = 'Request Timed Out';
				}else {
					var message = 'Unknow Error.\n'+x.responseText;
				}

				jQuery.flash.error('Error', message)
			}
		});
	}
)


/**
* this pops up a "add existing" popup. Currently only used by the model editor, however it will likely be modified to be used as part
* of the
*/
function popupSelectExisting(modelType, relatedModelType, relatedModelId, relationName, onSuccess){
	 runWizard("/cms/modelEditor/findExisting/listModelType/"+ modelType +"/relatedModelType/"+relatedModelType+"/relationName/"+ relationName + "/relatedModelId/" + relatedModelId, {}, onSuccess, {}, {});
}


/**
* This will open up a datagrid listing a specific model type. on sucecss is called when an item in the datagrid is selected.
*/
function popupDatagrid(modelType, onSuccess, onCancel, onLoad){
	 runWizard("/Core/datagrid/index/modelType/" + modelType , {}, onSuccess, onCancel, onLoad);
}


function runRelations(wizardUrl,  boxTitle, onClose){
	runIndependentPopup(wizardUrl, boxTitle, onClose);
}


function runWizard(wizardUrl, additionalData, onSuccess, onCancel, onLoad ){
	runInPopup(wizardUrl, additionalData, onSuccess, onCancel, onLoad, 475, 600);
}




/**
*@hack: to allow relation editor to poup widgets...
*/
function runIndependentPopup(wizardUrl, boxTitle, onClose){
	var src = "";

	if (wizardUrl){
		if (wizardUrl.substring(0,4) == "http"){
			src = wizardUrl;
		}
		else {
			src = b_projectUrl + wizardUrl;
		}
	}

	window.top.independentbox = $("<div style='overflow:hidden;'><iframe frameborder='0' height='"+650+"' width='100%' scrolling='auto' name='popupIframe' id='popupIframe' src='" + src + "'>Loading...</iframe></div>");

	independentPopup = window.top.independentbox.dialog(
		{
			zIndex: 1000000,
			width: "90%",
			closeOnEscape: true,
			draggable: false,
			modal: true,
			resizable: false,
			title: boxTitle,
            beforeclose:
				function(event, ui) {

					onClose(window.top.independentData);
					window.top.independentData = null;
					window.top.independentbox = null;

					return true;
				}
		}
	);
}

/**
* This opens up a popup pointing to a particular URL. There is currently a bit of an issue with being able to pass
* params to this window - as we are limited essentially to a "get" request.
*
* wizardUrl = the url to the wizard, relative to the project url
* additionalData = a JSON object containing key:value pairs of parmas we want to pass in.
* onSuccess = function to call when wizard succeeds
* onCancel = function to call if wizard cancelled
* onLoad = function to call when wizard loaded.
*/
function runInPopup(wizardUrl, additionalData, onSuccess, onCancel, onLoad, height, width){
	if (window.top.wizard != null){
		alert("Unable to launch wizard - another wizard looks to be in progress");
		return;
	}

	var src = "";


	if (wizardUrl){
		if (wizardUrl.substring(0,4) == "http"){
			src = wizardUrl;
		}
		else {
			src = b_projectUrl + wizardUrl;
		}
	}

	var autosizer;

	popupBox = $("<div style='overflow:hidden;'><iframe frameborder='0' height='"+height+"' width='100%' scrolling='auto' name='popupIframe' id='popupIframe' src='" + src + "'>Loading...</iframe></div>");

	window.top.wizard = popupBox.dialog(
		{
			zIndex: 1000000,
			width: width,
			closeOnEscape: true,
			draggable: false,
			modal: true,
			resizable: false,
			title: '',
			open: function(event, ui){if (onLoad!==undefined){  onLoad;}},
			beforeclose:
				function(event, ui) {

					if (window.top.wizardData !== null){
						onSuccess(window.top.wizardData);
					} else {
						//window.top.onCancel();
					}

					window.top.wizardData = null;
					window.top.wizard = null;

					return true;
				}
		}
	);
}

/**
* function is intended to keep the iframe resizing at a particular interval to the
* size of the document within the iframe. It needs to constantly check/resize because
* some DOMs are altered once the document has already rendered. (i.e. a custom form
* that keeps adding elements).
*/

function autoSizeIframe(iframe){

    if (typeof($('#' + iframe).get(0))=="undefined"){
        return;
    }

	var innerHTML = ($('#' + iframe).get(0).contentDocument) ? $('#' + iframe).get(0).contentDocument : $('#' + iframe).get(0).contentWindow.document;
	var height = $(innerHTML.body).height();
	var width = $(innerHTML.body).width();
	$('#' + iframe).height(height + 30); //add 30 to take care of the horizontal scrollbar....
	/*if (width > $('#' + iframe).width()){
		$('#' + iframe).width(width);
	}*/
}


function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}


function closeRelation(data){
	window.top.independentData = data;
	window.top.independentbox.dialog("close");
}

